Powershell的Invoke-Command不会为-ComputerName参数接受变量?

eri*_*avg 6 powershell powershell-2.0 powershell-remoting

我把头发拉到这里,因为我似乎无法让它发挥作用,我无法弄清楚如何谷歌这个问题.我正在运行Powershell 2.0.这是我的脚本:

$computer_names = "server1,server2"
Write-Output "Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}"
Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}
Run Code Online (Sandbox Code Playgroud)

最后一个命令给出错误:

Invoke-Command : One or more computer names is not valid. If you are trying to 
pass a Uri, use the -ConnectionUri parameter or pass Uri objects instead of 
strings.
Run Code Online (Sandbox Code Playgroud)

但是当我将Write-Output命令的输出复制到shell并运行它时,它可以正常工作.如何将字符串变量转换为Invoke-Command将接受的内容?提前致谢!

And*_*ykh 6

Jamey和user983965是正确的,因为你的声明是错误的.但这foreach不是强制性的.如果您只修复这样的数组声明,它将起作用:

$computer_names = "server1","server2"
Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}
Run Code Online (Sandbox Code Playgroud)


Jam*_*mey 5

您错误地声明了数组.在字符串之间加一个逗号并将它管道为for-each,如:

$computer_names = "server1", "server2";

$computer_names | %{
   Write-Output "Invoke-Command -ComputerName $_ -ScriptBlock {

    ...snip
Run Code Online (Sandbox Code Playgroud)