我把头发拉到这里,因为我似乎无法让它发挥作用,我无法弄清楚如何谷歌这个问题。我正在运行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将接受的内容?提前谢谢!
答案 0 :(得分: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
}
答案 1 :(得分:5)
您错误地声明了数组。在字符串之间加一个逗号并将其管道为 - 每个像:
$computer_names = "server1", "server2";
$computer_names | %{
Write-Output "Invoke-Command -ComputerName $_ -ScriptBlock {
...snip
答案 2 :(得分:0)
你试过了吗?
$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
}
}
答案 3 :(得分:0)
如果你也从活动目录中获取了一系列计算机 - 就像这样:
$ computers = Get-ADComputer -filter {whatever}
确保您记得选择/展开结果..像这样:
$ Computers = Get-ADComputer -filter * | Select-Object -ExpandProperty Name
则...
Invoke-Command -ComputerName $ Computers -ScriptBlock {Do Stuff}