Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 327
erictheavg Avatar asked Apr 10 '12 20:04

erictheavg


People also ask

How do you pass arguments to invoke a command?

To pass the argument in the Invoke-command, you need to use -ArgumentList parameter.

How do you store a command in a variable in PowerShell?

You can assign a command to a variable in the same way that you would assign a constant value to a variable. Just enter the variable name, followed by an equal sign, and the command.

How do I run a PowerShell script from a parameter?

You can run scripts with parameters in any context by simply specifying them while running the PowerShell executable like powershell.exe -Parameter 'Foo' -Parameter2 'Bar' . Once you open cmd.exe, you can execute a PowerShell script like below.

How do I set the value of a variable in PowerShell?

To display the value of a variable, type the variable name, preceded by a dollar sign ( $ ). To change the value of a variable, assign a new value to the variable. The following examples display the value of the $MyVariable variable, changes the value of the variable, and then displays the new value.


1 Answers

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 
}
like image 172
Andrew Savinykh Avatar answered Oct 02 '22 19:10

Andrew Savinykh