2

我正在运行以下 powershell 命令:

$cmd = "xxx.exe"

Invoke-Command -ComputerName localhost {Invoke-Expression $cmd}

但是我得到了错误:

Cannot bind argument to parameter 'Command' because it is null.

+ CategoryInfo          : InvalidData: (:) [Invoke-Expression], ParameterB
indingValidationException
 + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,M
icrosoft.PowerShell.Commands.InvokeExpressionCommand
4

2 回答 2

4

查看Invoke-Command.

使用-ArgumentList参数或者如果 powershell 3 参见示例 9 ( $Using:)。

http://technet.microsoft.com/en-us/library/hh849719.aspx

参数列表示例 -

$cmd = "xxx.exe"
Invoke-Command -ComputerName localhost {Invoke-Expression $args[0]} -ArgumentList $cmd

如果param在脚本块中使用,则可以使用命名参数而不是$args内置参数。

于 2014-08-15T12:14:11.173 回答
0

我将向您展示我这样做的方式,传递一个文件-FilePath并传递参数-ArgumentList

我创建了一个包含我要执行的代码的函数。

#remote_functions.ps1
param($command, $param1, $param2, $param3, $param4, $param5)
$ScriptVersion = "1.0"

function Write5Strings($string1, $string2, $string3, $string4, $string5)
{
    Write-Host "String1: $string1"
    Write-Host "String2: $string2"
    Write-Host "String3: $string3"
    Write-Host "String4: $string4"
    Write-Host "String5: $string5"
    throw "ERROR"
}


try
{
    &$command $param1 $param2 $param3 $param4 $param5
}
catch [System.Exception]
{
    Write-Error $_.Exception.ToString()
    exit 1
} 

我这样调用它:

$server="server"
$remotingPort=81

$job = Invoke-Command -AsJob -Port $remotingPort -ComputerName $server -FilePath ".\remote_functions.ps1" -ArgumentList @("Write5Strings", "apple", "banana", "orange", "pear", "watermelon")

还要检查这个问题:如何使用 Invoke-Command 传递命名参数?

于 2014-08-15T12:44:26.480 回答