从Powershell脚本中提取AST

时间:2018-07-09 17:38:21

标签: powershell abstract-syntax-tree

给出一个powershell脚本(例如$ C = $ a + $ b; $ d = $ e * $ f),我试图访问脚本AST中的每个节点。

目前,我已经尝试过:

$code = {$C=$a+$b; $d = $e*$f}
$astVisitor = [System.Management.Automation.Language.AstVisitor]
$visit = $code.Ast.Visit($astVisitor)

但是我遇到了以下错误:找不到“ Visit”和参数计数:“ 1”的重载。

什么是访问ast数据结构并正确使用visit方法循环遍历树中每个节点的正确方法?我发现ast api的文档没有什么帮助。

非常感谢!

1 个答案:

答案 0 :(得分:1)

  

我正在尝试访问脚本AST中的每个节点

如果您只是想自己查看嵌套的元素,请使用FindAll()方法:

$code.Ast.FindAll({$true},$true)

第一个参数是一个回调引用,可用于过滤结果-例如,如果仅想提取字符串表达式,则可以执行以下操作:

$code = {
  "A string"
  123
  Get-Process
  & {
    'Another string'
  }
}

$Code.Ast.FindAll({
  param($Ast) 

  $Ast -is [System.Management.Automation.Language.StringConstantExpressionAst]
}, $true)

第二个参数是一个布尔值,指示是否遍历嵌套的脚本块。使用上面的示例,但是将第二个参数值更改为$false会产生相同的结果,除了第二个字符串。

已经存在用于在GUI中可视化树的几个工具,例如ShowPSAstASTExplorer

如果要使用AstVisitor,请在PowerShell 5.0中使用here's an example of implementing the ICustomAstVisitor界面。

上面的示例来自3.0 SDK中的ScriptLineProfiler示例。注意VisitStatements()方法中对语句的修改,应该给您一些有关如何修改/重新创建单个节点的想法