Function 使用Powershell自省查找作为参数传递的函数的名称?
比如说,有没有办法通过powershell中的内省来找出传递的函数的名称?或者我只需要将其与其他参数一起传递Function 使用Powershell自省查找作为参数传递的函数的名称?,function,powershell,introspection,Function,Powershell,Introspection,比如说,有没有办法通过powershell中的内省来找出传递的函数的名称?或者我只需要将其与其他参数一起传递 (不调用有问题的函数)链接的问题试图以字符串形式按名称传递函数,在这种情况下,答案显而易见:参数本身就是函数名 如果传递了脚本块,则可以使用以下技术: function get-ScriptBlockCommandName { param( [scriptblock] $ScriptBlock, [switch] $Expand ) # Using the
(不调用有问题的函数)链接的问题试图以字符串形式按名称传递函数,在这种情况下,答案显而易见:参数本身就是函数名 如果传递了脚本块,则可以使用以下技术:
function get-ScriptBlockCommandName {
param(
[scriptblock] $ScriptBlock,
[switch] $Expand
)
# Using the script block's AST, extract the first command name / path token.
$commandName = $ScriptBlock.Ast.EndBlock.
Statements[0].PipelineElements.CommandElements[0].Extent.Text
# Expand (interpolate) the raw name, if requested.
if ($Expand) {
$commandName = $ExecutionContext.InvokeCommand.ExpandString($commandName)
}
# Remove outer quoting, if present.
if ($commandName -match '^([''"])(.+)\1$') {
$commandName = $Matches[2]
if ($Matches[1] -eq "'") { $commandName = $commandName -replace "''", "'" }
}
# Output
$commandName
}
该函数返回从脚本块内部调用的(第一个)命令名/路径
注意事项:
- 如果将表达式(例如,
)作为脚本块内的第一条语句传递,则会发生错误1+2
- 只分析第一个命令(并返回其命令名/路径),而对可以在脚本块中放置的语句数量没有限制
- 默认情况下,如果命令名/路径是由变量/其他命令构造的,则这些命令不会展开(插值),因为这样做可能导致命令的执行;要选择展开,请使用
开关-Expand
PS> get-ScriptBlockCommandName { foo -bar baz -more stuff }
foo
这也适用于带引号的名称/路径(注意如何使用&
调用命令):
但是,为了避免可能不需要的命令执行,命令名/路径按原样返回,变量引用和子表达式未展开。您可以通过传递
-Expand
,选择将其展开:
PS> get-ScriptBlockCommandName { & "$HOME/scripts/foo.ps1" -bar baz } -Expand
C:/Users/jdoe/scripts.ps1 # e.g.
PS> get-ScriptBlockCommandName { & "$HOME/scripts/foo.ps1" -bar baz } -Expand
C:/Users/jdoe/scripts.ps1 # e.g.