具有动态函数名称的Invoke-Command

Den*_*s G 4 powershell powershell-remoting

我找到了这个很棒的帖子:在带参数的函数上使用Invoke-Command -ScriptBlock

我正在尝试使函数call(${function:Foo})动态,因为我想传递函数名称.

我试过这个:

$name = "Foo"
Invoke-Command -ScriptBlock ${function:$name}
Run Code Online (Sandbox Code Playgroud)

但那失败了.我也尝试了各种转义序列,但是不能让函数名称变为动态.


编辑:为了清楚起见,我添加了一个小测试脚本.当然,期望的结果是打电话给ExternalFunction.

Function ExternalFunction()
{
  write-host "I was called externally"
}

Function InternalFunction()
{
    Param ([parameter(Mandatory=$true)][string]$FunctionName)
    #working: Invoke-Command -ScriptBlock ${function:ExternalFunction}
    #not working: Invoke-Command -ScriptBlock ${invoke-expression $FunctionName}
    if (Test-Path Function:\$FunctionName) {
    #working,but how to use it in ScriptBlock?
    }
}

InternalFunction -FunctionName "ExternalFunction"
Run Code Online (Sandbox Code Playgroud)

mjo*_*nor 6

替代解决方案:

function foo {'I am foo!'}

$name = 'foo'

$sb = (get-command $name -CommandType Function).ScriptBlock
invoke-command -scriptblock $sb
Run Code Online (Sandbox Code Playgroud)

我很好!

  • 仅供将来参考,如果您将其与具有 Begin、Process 或 End 块的高级函数一起使用,这实际上会失败。您将收到有关包含多个子句的例外情况。不过,您可以通过使用调用运算符而不是 Invoke-Command 来解决这个问题。所以像这样:&$sb“某些功能参数” (2认同)