6

I'm pulling my hair out here, because I just can't seem to get this to work, and I can't figure out how to google this issue. I'm running Powershell 2.0. Here's my script:

$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 
}

The last command gives the error:

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.

But when I copy the output of the Write-Output command to the shell and run that, it works just fine. How can I cast the string variable to something that Invoke-Command will accept? Thanks in advance!

4

4 回答 4

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 
}
于 2012-04-10T21:15:17.787 回答
5

您错误地声明了您的数组。在字符串之间放置一个逗号并将其通过管道传递给 for-each,例如:

$computer_names = "server1", "server2";

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

    ...snip
于 2012-04-10T21:01:47.380 回答
1

如果您也从活动目录中获取一组计算机 - 像这样:

$computers = Get-ADComputer -filter {whatever}

确保你记得选择/展开结果..像这样:

$Computers= 获取 ADComputer -filter * | Select-Object -ExpandProperty 名称

然后...

调用命令 -ComputerName $Computers -ScriptBlock {Do Stuff}

于 2016-01-15T21:41:18.467 回答
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 
}
}
于 2012-04-10T21:02:09.513 回答