2017-03-02 34 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

相關問題