AST是去静态(ISH)分析的方式。下面是我会怎么做你所描述的
$rs = [runspacefactory]::CreateRunspace()
$rs.Open()
# Get the AST of the file
$tokens = $errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseFile(
'MyScript.ps1',
[ref]$tokens,
[ref]$errors)
# Get only function definition ASTs
$functionDefinitions = $ast.FindAll({
param([System.Management.Automation.Language.Ast] $Ast)
$Ast -is [System.Management.Automation.Language.FunctionDefinitionAst] -and
# Class methods have a FunctionDefinitionAst under them as well, but we don't want them.
($PSVersionTable.PSVersion.Major -lt 5 -or
$Ast.Parent -isnot [System.Management.Automation.Language.FunctionMemberAst])
}, $true)
# Add the functions into the runspace
$functionDefinitions | ForEach-Object {
$rs.SessionStateProxy.InvokeProvider.Item.Set(
'function:\{0}' -f $_.Name,
$_.Body.GetScriptBlock())
}
# Get help within the runspace.
$ps = [powershell]::Create().AddScript('Get-Help MyFunction')
try {
$ps.Runspace = $rs
$ps.Invoke()
} finally {
$ps.Dispose()
}
你可以从靠近顶部,如果你想要去一个纯粹的静态路由也使用$tokens
。评论将不会在AST中,但它们将在令牌中。
编辑上面的方法实际上在进程中的某处丢失了注释帮助,这不是因为运行空间,而仅仅是因为函数是如何分配的。可能由于评论不是真的是是AST的一部分。无论如何,有一种更直接和更静态的方式来获得帮助。
而不是定义的功能,你可以使用FunctionDefinitionAst
$helpContent = $functionDefinitions | ForEach-Object { $_.GetHelpContent() }
这个GetHelpContent
方法将返回一个对象CommentHelpInfo每个功能。请注意,这是而不是与Get-Help
cmdlet返回的相同对象。最值得注意的是它不区分代码和示例块中的描述。但是,如果您需要正常分析CBH,则可以获取注释块文本并定义您自己的假版本。
$helpContent = $functionDefinitions | ForEach-Object {
# Get the plain string comment block from the AST.
$commentBlock = $_.GetHelpContent().GetCommentBlock()
# Create a scriptblock that defines a blank version of the
# function with the CBH. You may lose some parameter info
# here, if you need that replace param() with
# $_.Body.ParamBlock.Extent.Text
$scriptBlock = [scriptblock]::Create(('
function {0} {{
{1}
param()
}}' -f $_.Name, $commentBlock))
# Dot source the scriptblock in a different scope so we can
# get the help content but still not pollute the session.
& {
. $scriptBlock
Get-Help $_.Name
}
}
相关:http://www.ravichaganti.com/blog/powershell-ise-addon-ise-function-explorer-using-the-powershell-3-0-parser/ – Matt