如何在 powershell 中使用 AST 查找脚本方法?

How to find scriptmethod using AST in powershell?

我有以下脚本。

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 个脚本方法 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}

您最后只在 foreach 中选择了名称 属性。虽然类型 [System.Management.Automation.Language.FunctionDefinitionAst] 可能有名称 属性,但 [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"
                  }