我把头发拉到这里,因为我似乎无法让它发挥作用,我无法弄清楚如何谷歌这个问题。我正在运行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
}
最后一个命令给出错误:
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.
但是当我将Write-Output命令的输出复制到shell并运行它时,它可以正常工作。如何将字符串变量转换为Invoke-Command将接受的内容?提前致谢!
您错误地声明了数组。在字符串之间加一个逗号并将它管道为for-each,如:
$computer_names = "server1", "server2";
$computer_names | %{
Write-Output "Invoke-Command -ComputerName $_ -ScriptBlock {
...snip
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
}
你有没有尝试过:
$computer_names = "server1" , "server2"
foreach ($computer in $computer_names)
{
Write-Output "Invoke-Command -ComputerName $computer -ScriptBlock {
Get-WmiObject -Class Win32_LogicalDisk |
sort deviceid |
Format-Table -AutoSize deviceid, freespace
}"
Invoke-Command -ComputerName $computer -ScriptBlock {
Get-WmiObject -Class Win32_LogicalDisk |
sort deviceid |
Format-Table -AutoSize deviceid, freespace
}
}
如果你从活动目录中获得一组计算机 - 就像这样:
$ computers = Get-ADComputer -filter {whatever}
确保你记得选择/扩展结果..像这样:
$ Computers = Get-ADComputer -filter * | Select-Object -ExpandProperty Name
然后...
Invoke-Command -ComputerName $ Computers -ScriptBlock {Do Stuff}