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