Gil*_*sak 3 powershell abstract-syntax-tree
给定一个 powershell 脚本(例如 $C=$a+$b; $d = $e*$f),我尝试访问脚本 AST 中的每个节点。
\n\n目前,我\xe2\x80\x99已经尝试过:
\n\n$code = {$C=$a+$b; $d = $e*$f}\n$astVisitor = [System.Management.Automation.Language.AstVisitor]\n$visit = $code.Ast.Visit($astVisitor)\nRun Code Online (Sandbox Code Playgroud)\n\nbut I\xe2\x80\x99m running into the following error: Cannot find an overload for "Visit" and the argument count: "1".
\n\nWhat\'s the right way to access the ast data structure and use the visit method correctly to loop through every node in the tree? I didn\'t find the documentation of the ast api very helpful.
\n\nThanks very much!
\n我正在尝试访问脚本 AST 中的每个节点
如果您只想亲自查看嵌套元素,请使用以下FindAll()方法:
$code.Ast.FindAll({$true},$true)
Run Code Online (Sandbox Code Playgroud)
第一个参数充当谓词,您可以使用它来过滤结果。
例如,如果您只想提取字符串表达式,您可以这样做:
$code = {
"A string"
123
Get-Process
& {
'Another string'
}
}
$Code.Ast.FindAll({
param($Ast)
$Ast -is [System.Management.Automation.Language.StringConstantExpressionAst]
}, $true)
Run Code Online (Sandbox Code Playgroud)
第二个参数是一个布尔值,指示是否遍历嵌套脚本块。使用上面的示例,但将第二个参数值更改为$false将产生相同的结果(第二个字符串除外)。
已经存在一些用于在 GUI 中可视化树的工具,例如ShowPSAst和ASTExplorer。
如果您想使用 AstVisitor,这里有一个在 PowerShell 5.0 中实现该接口的示例。ICustomAstVisitor
上面的示例来自 3.0 SDK 中的 ScriptLineProfiler 示例。注意方法中语句的修改VisitStatements(),应该会给您一些关于如何修改/重新创建各个节点的想法
| 归档时间: |
|
| 查看次数: |
1094 次 |
| 最近记录: |