Question:
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:
1 2 3 4 5 6 7 8 9 10 11 12 |
$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:
1 2 3 4 |
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!
Answer:
You declared your array incorrectly. Put a comma between strings and pipe it to for-each like:
1 2 3 4 5 6 7 |
$computer_names = "server1", "server2"; $computer_names | %{ Write-Output "Invoke-Command -ComputerName $_ -ScriptBlock { ...snip |