我有以下脚本。
function Sample-function
{
Write-host "I am function"
}
function Sample-ScriptMethod
{
$obj = [pscustomobject]@{}
$obj | Add-Member -MemberType ScriptMethod -Name sm1 -Value {
Write-host "I am scriptmethod1"
}
Write-host "I am troubling"
$obj | Add-Member -MemberType ScriptMethod -Name sm2 -Value {
Write-host "I am scriptmethod2"
}
$obj
}
使用AST我能够找到如下的函数名称。
function GEt-functionNames
{
Param
(
$filepath="C:\repo\UnMapStress2\g2\lib\Common\Windows\NWPSF\tests\lib\Common\IOOperation.psm1"
)
$AST = [System.Management.Automation.Language.Parser]::ParseFile($filepath,[ref]$null,[ref]$Null)
# Returns function name
$AST.FindAll({$args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst]},$true) | foreach { $_.name}
}
Get-functionNames -filepath "C:\Users\Administrator\Desktop\ASTSample.ps1"
输出
Sample-function
Sample-ScriptMethod
我也想在文件中找到脚本方法。该文件有2个scriptmethods sm1和sm2。
如何在powershell中找到它们? AST有找到它的方法吗?
更新: 我试图找到使用以下方式,但无法找到
$filepath = "C:\Users\Administrator\Desktop\ASTSample.ps1"
$AST = [System.Management.Automation.Language.Parser]::ParseFile($filepath,[ref]$null,[ref]$Null)
# Returns function name
$AST.FindAll({$args[0] -is [System.Management.Automation.Language.ScriptBlockExpressionAst]},$true) | foreach { $_.name}
答案 0 :(得分:2)
您最后只在foreach中选择了Name属性。虽然类型[System.Management.Automation.Language.FunctionDefinitionAst]
可能具有Name属性,但[System.Management.Automation.Language.ScriptBlockExpressionAst]
却没有。
如果从代码中删除foreach,则可以看到ScriptBlocks。
# $AST = [System.Management.Automation.Language.Parser]::ParseFile($filepath,[ref]$null,[ref]$Null)
# $AST.FindAll({$args[0] -is [System.Management.Automation.Language.ScriptBlockExpressionAst]},$true) | fl
ScriptBlock : {
Write-host "I am scriptmethod1"
}
StaticType : System.Management.Automation.ScriptBlock
Extent : {
Write-host "I am scriptmethod1"
}
Parent : Add-Member -MemberType ScriptMethod -Name sm1 -Value {
Write-host "I am scriptmethod1"
}
ScriptBlock : {
Write-host "I am scriptmethod2"
}
StaticType : System.Management.Automation.ScriptBlock
Extent : {
Write-host "I am scriptmethod2"
}
Parent : Add-Member -MemberType ScriptMethod -Name sm2 -Value {
Write-host "I am scriptmethod2"
}