PowerShell AST FindAll方法使用$args[0]获取脚本块
我一直在使用PowerShell AST为PSScript Analyzer创建一些自定义规则 在AST的许多示例代码中,有一行我不理解。这里有一个例子 首先解析一个文件,在本例中是ISE中当前打开的文件PowerShell AST FindAll方法使用$args[0]获取脚本块,powershell,abstract-syntax-tree,Powershell,Abstract Syntax Tree,我一直在使用PowerShell AST为PSScript Analyzer创建一些自定义规则 在AST的许多示例代码中,有一行我不理解。这里有一个例子 首先解析一个文件,在本例中是ISE中当前打开的文件 $AbstractSyntaxTree = [System.Management.Automation.Language.Parser]:: ParseInput($psISE.CurrentFile.Editor.Text, [ref]$null, [r
$AbstractSyntaxTree = [System.Management.Automation.Language.Parser]::
ParseInput($psISE.CurrentFile.Editor.Text, [ref]$null, [ref]$null)
到目前为止,这是有道理的。假设我们要查找所有参数化对象。下面是我看到的代码
$params = $AbstractSyntaxTree.FindAll({$args[0] -is [System.Management.Automation.Language.ParameterAst]}, $true)
这行代码正在调用FindAll
并传入一个脚本块,该脚本块似乎起到了过滤器的作用,因此只返回参数化对象
我不明白的是,
$args[0]
如何适应这个调用。调用FindAll
方法时,任何参数实际上是如何传递到scriptblock的?将scriptblock视为匿名回调函数
这与使用Where对象{$someCondition}
时发生的情况完全相同
查找所有内容,并为每个内容调用您提供的函数。它显然期望得到一个[bool]
结果,并返回满足回调中存在的条件的对象
在powershell中的函数、脚本或脚本块中,可以有显式定义的命名参数,也可以有显式定义的命名参数,这就是这里发生的情况
将scriptblock用作回调与将其用于事件类似:
$Args
Contains an array of the undeclared parameters and/or parameter
values that are passed to a function, script, or script block.
When you create a function, you can declare the parameters by using the
param keyword or by adding a comma-separated list of parameters in
parentheses after the function name.
In an event action, the $Args variable contains objects that represent
the event arguments of the event that is being processed.
FindAll
方法具有以下签名(来自):
public IEnumerable作为输入,并返回bool。
在Powershell中,您可以创建这样的委托:
$delegate={param($ast)$ast-is[System.Management.Automation.Language.ParameterAst]}
或不声明参数:
$delegate={$args[0]-is[System.Management.Automation.Language.ParameterAst]}
FindAll
方法将执行类似的操作(伪代码):
foreach($allNodes中的节点){
$shoulddad=&$delegate$node