使用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
}
感謝您的回答。你能建議一些網站/博客瞭解更多關於此? – user7645525
我不記得了,但我想我在C#中找到了一些例子並對它們進行了修改。也許那些在MSDN文檔鏈接在我的答案。 – wOxxOm