Search code examples
powershellpowershell-2.0powershell-remoting

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


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!


Solution

  • You declared your array incorrectly. Put a comma between strings and pipe it to for-each like:

    $computer_names = "server1", "server2";
    
    $computer_names | %{
       Write-Output "Invoke-Command -ComputerName $_ -ScriptBlock {
    
        ...snip