问题描述
我正在编写一个 PowerShell 脚本,该脚本将使用 在远程主机上执行命令Invoke-Command 及其 -ScriptBlock
参数.例如,
I'm writing a PowerShell script that will execute commands on a remote host using Invoke-Command and its -ScriptBlock
parameter. For example,
function Foo {
...
return "foo"
}
$rv = Invoke-Command --Credential $c --ComputerName $fqdn -ScriptBlock ${function:Foo}
这很好用.我现在想做的是同样的事情,但调用带有本地参数的函数.例如,
This works fine. What I'd like to do now is the same thing, but call a function with local arguments. For example,
function Bar {
param( [String] $a, [Int] $b )
...
return "foo"
}
[String] $x = "abc"
[Int] $y = 123
$rv = Invoke-Command --Credential $c --ComputerName $fqdn -ScriptBlock ${function:Foo($x,$y)}
但这不起作用:
调用命令:无法验证参数ScriptBlock"上的参数.参数为空.提供一个非空参数并尝试命令再次.
如何将 Invoke-Command 与带有参数的本地函数 -ScriptBlock
一起使用?
How can I use Invoke-Command with a -ScriptBlock
that is a local function with arguments?
我意识到我可以将整个函数和参数包装在一个大代码块中,但在我看来,这不是一种干净的方法.
I realize that I can wrap the entire function and the parameters in a big code block, but that is not a clean way of doing it, in my opinion.
推荐答案
我想你想要:
function Foo ( $a,$b) {
$a
$b
return "foo"
}
$x = "abc"
$y= 123
Invoke-Command -Credential $c -ComputerName $fqdn -ScriptBlock ${function:Foo} -ArgumentList $x,$y
这篇关于在带参数的函数上使用 Invoke-Command -ScriptBlock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!