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

时间:2013-02-09 15:27:25

标签: powershell powershell-remoting

我找到了这个很棒的帖子:Using Invoke-Command -ScriptBlock on a function with arguments

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

我试过了:

$name = "Foo"
Invoke-Command -ScriptBlock ${function:$name}

但是失败了。我也尝试了各种转义序列,但只是无法使函数名称变为动态。


编辑:为了清楚起见,我正在添加一个小测试脚本。当然,期望的结果是调用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"

3 个答案:

答案 0 :(得分:6)

替代解决方案:

function foo {'I am foo!'}

$name = 'foo'

$sb = (get-command $name -CommandType Function).ScriptBlock
invoke-command -scriptblock $sb

我很好!

答案 1 :(得分:2)

您可以尝试以下方法。它会在尝试运行它之前测试指定的名称是否为有效函数:

$myfuncnamevar = "Foo"
Invoke-Command -ScriptBlock {
    param($name)
    if (Test-Path Function:\$name) { 
        #Function exists = run it
        & $name
    }
} -ArgumentList $myfuncnamevar

答案 2 :(得分:1)

简单如下:

invoke-expression  $name

或者如果要保留用于远程处理的invoke-command,例如

Invoke-Command -ScriptBlock { invoke-expression  $name}
相关问题