[英]Invoke-Command with dynamic function name
I found this awesome post: Using Invoke-Command -ScriptBlock on a function with arguments 我找到了这个很棒的帖子: 在带参数的函数上使用Invoke-Command -ScriptBlock
I'm trying to make the function call ( ${function:Foo}
) dynamic, as in I want to pass the function name. 我正在尝试使函数调用(
${function:Foo}
)动态,因为我想传递函数名称。
I tried this: 我试过这个:
$name = "Foo"
Invoke-Command -ScriptBlock ${function:$name}
but that fails. 但那失败了。 I also tried various escape sequences, but just can't get the function name to be dynamic.
我也尝试了各种转义序列,但是不能让函数名称变为动态。
EDIT: For clarity I am adding a small test script. 编辑:为了清楚起见,我添加了一个小测试脚本。 Of course the desired result is to call the
ExternalFunction
. 当然,期望的结果是调用
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"
Alternate solution: 替代解决方案:
function foo {'I am foo!'}
$name = 'foo'
$sb = (get-command $name -CommandType Function).ScriptBlock
invoke-command -scriptblock $sb
I am foo! 我很好!
You could try the following. 您可以尝试以下方法。 It tests if the name specified is a valid function before it attempts to run it:
它会在尝试运行它之前测试指定的名称是否为有效函数:
$myfuncnamevar = "Foo"
Invoke-Command -ScriptBlock {
param($name)
if (Test-Path Function:\$name) {
#Function exists = run it
& $name
}
} -ArgumentList $myfuncnamevar
as simple as : 很简单:
invoke-expression $name
or if you want to keep invoke-commande for remoting for example 或者如果你想保持invoke-commande用于远程处理,例如
Invoke-Command -ScriptBlock { invoke-expression $name}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.