2017-03-02 50 views
2

如何提取PowerShell函数定义的内容? 假设代码是这样,使用PowerShell从文件中提取函数体

Function fun1($choice){ 
    switch($choice) 
    { 
     1{ 
     "within 1" 
     } 
     2{ 
     "within 2" 
     } 
     default{ 
     "within default" 
     } 

    } 

} 

fun1 1 

我只想要函数的定义,并没有其他的文本内容。

回答

3

使用PowerShell 3.0+ Language namespace AST解析器:

$code = Get-Content -literal 'R:\source.ps1' -raw 
$name = 'fun1' 

$body = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null). 
    Find([Func[Management.Automation.Language.Ast,bool]]{ 
     param ($ast) 
     $ast.name -eq $name -and $ast.body 
    }, $true) | ForEach { 
     $_.body.extent.text 
    } 

输出单一的多行字符串在$体:

{ 
    switch($choice) 
    { 
     1{ 
     "within 1" 
     } 
     2{ 
     "within 2" 
     } 
     default{ 
     "within default" 
     } 

    } 

} 

要提取的第一个函数定义体,无论名称:

$body = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null). 
    Find([Func[Management.Automation.Language.Ast,bool]]{$args[0].body}, $true) | ForEach { 
     $_.body.extent.text 
    } 

提取从开始的整个函数定义关键字,使用$_.extent.text

$fun = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null). 
    Find([Func[Management.Automation.Language.Ast,bool]]{$args[0].body}, $true) | ForEach { 
     $_.extent.text 
    } 
+0

感谢您的回答。你能建议一些网站/博客了解更多关于此? – user7645525

+0

我不记得了,但我想我在C#中找到了一些例子并对它们进行了修改。也许那些在MSDN文档链接在我的答案。 – wOxxOm

相关问题