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)
替代解决方案:
function foo {'I am foo!'}
$name = 'foo'
$sb = (get-command $name -CommandType Function).ScriptBlock
invoke-command -scriptblock $sb
Run Code Online (Sandbox Code Playgroud)
我很好!
| 归档时间: |
|
| 查看次数: |
5661 次 |
| 最近记录: |