windows 使用 Powershell 的 Invoke-Command 调用带参数的批处理文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8541809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:02:10  来源:igfitidea点击:

Using Powershell's Invoke-Command to call a batch file with arguments

windowspowershellbatch-filecmdletsinvoke-command

提问by Jay Spang

I want to use Powershell in order to call a batch file on remote machines. This batch file has arguments. Here's what I have so far:

我想使用 Powershell 来调用远程机器上的批处理文件。这个批处理文件有参数。这是我到目前为止所拥有的:

$script = "\fileshare\script.cmd"
$server = $args[0]
$args [string]::join(',',$args[1 .. ($args.count-1)])

Invoke-Command -computername $server {$script + ' ' + $args}

After a bit of searching, I found that the Invoke-Command function runs its scriptblock in a whole new process, so you can't put variables in it (they won't get expanded). That's what the -ArgumentList tag is for. So I tried this instead...

经过一番搜索,我发现 Invoke-Command 函数在一个全新的进程中运行其脚本块,因此您不能在其中放置变量(它们不会被扩展)。这就是 -ArgumentList 标签的用途。所以我尝试了这个......

Invoke-Command -computername $server {\fileshare\script.cmd} -ArgumentList "FirstArgument"

That didn't work either... my batch script tells me it's not being passed any arguments. I can't find anything that explicitly says so, but it looks like the -ArgumentList parameter only works on Powershell scripts (it won't feed them to a batch script).

这也不起作用......我的批处理脚本告诉我它没有被传递任何参数。我找不到任何明确说明的内容,但看起来 -ArgumentList 参数仅适用于 Powershell 脚本(它不会将它们提供给批处理脚本)。

Any ideas how I can use Invoke-Command to call a batch file with arguments?

任何想法如何使用 Invoke-Command 调用带参数的批处理文件?

采纳答案by zdan

When you pass the argument list to the scriptblock, try to "receive them" using a PARAM directive. Like this:

当您将参数列表传递给脚本块时,尝试使用 PARAM 指令“接收它们”。像这样:

Invoke-Command -computername $server {PARAM($myArg) \fileshare\script.cmd $myArg} -ArgumentList "FirstArgument"

or you can just use the $args automatic variable:

或者你可以只使用 $args 自动变量:

Invoke-Command -computername $server {\fileshare\script.cmd $args} -ArgumentList "FirstArgument"

回答by manojlds

The arguments will be passed as arguments to the scriptblock and not directly to your cmd. You have to do:

这些参数将作为参数传递给脚本块,而不是直接传递给您的 cmd。你必须要做:

Invoke-Command {param($script,$arg1) &$script $arg1 } -computername $server -ArgumentList $script,"FirstArgument"

or

或者

Invoke-Command {&$args[0] $args[1] } -computername $server -ArgumentList $script,"FirstArgument"

PS: I don't know what you are doing with $args [string]::join(',',$args[1 .. ($args.count-1)]), it is a syntax error

PS:我不知道你在做什么$args [string]::join(',',$args[1 .. ($args.count-1)]),这是一个语法错误