Powershell's Invoke-Command won't take in a variable for -ComputerName parameter?

erictheavg picture erictheavg · Apr 10, 2012 · Viewed 13.5k times · Source

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!

Answer

Andrew Savinykh picture Andrew Savinykh · Apr 10, 2012

Jamey and user983965 are correct, in that your declaration is wrong. However foreach here is not mandatory. If you just fix your array declaration like this, it will work:

$computer_names = "server1","server2"
Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}