关于powershell:如何在“ Invoke-Expression”中将变量用作命令的参数

How to use variable as an argument for command in “Invoke-Expression”

本问题已经有最佳答案,请猛点这里访问。

我遇到了错误

Cannot bind argument to parameter 'Command' because it is null.
+ CategoryInfo : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
+ PSComputerName : X

当我尝试使用

1
2
$command ="cmd.exe /c $($currentLocation)/Ping.cmd"
Invoke-Command -ComputerName $systemName -credential $credentials -ScriptBlock {Invoke-Expression -Command: $command }

如何使用这样的变量? 我有这个要求,所以我不能直接使用它,它必须是动态的。


您可以将-ArgumentList参数与Invoke-Command一起使用,或者使用$using:访问变量,如下所示:

1
2
3
Invoke-Command -ComputerName $systemName -credential $credentials -ScriptBlock {
    Invoke-Expression -Command: $using:command
}