Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 使用Powershell自省查找作为参数传递的函数的名称?_Function_Powershell_Introspection - Fatal编程技术网

Function 使用Powershell自省查找作为参数传递的函数的名称?

Function 使用Powershell自省查找作为参数传递的函数的名称?,function,powershell,introspection,Function,Powershell,Introspection,比如说,有没有办法通过powershell中的内省来找出传递的函数的名称?或者我只需要将其与其他参数一起传递 (不调用有问题的函数)链接的问题试图以字符串形式按名称传递函数,在这种情况下,答案显而易见:参数本身就是函数名 如果传递了脚本块,则可以使用以下技术: function get-ScriptBlockCommandName { param( [scriptblock] $ScriptBlock, [switch] $Expand ) # Using the

比如说,有没有办法通过powershell中的内省来找出传递的函数的名称?或者我只需要将其与其他参数一起传递


(不调用有问题的函数)

链接的问题试图以字符串形式按名称传递函数,在这种情况下,答案显而易见:参数本身就是函数名

如果传递了脚本块,则可以使用以下技术:

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.