使用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