Powershell Invoke-Command does not accept variable for -ComputerName?

I am pulling my hair here because I just can't get it to work, and I can't figure out how to solve this problem. I am running Powershell 2.0. Here is 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 an 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 it, it works fine. How can I apply a string variable to what Invoke-Command accepts? Thanks in advance!

+6
source share
4 answers

You have incorrectly specified your array. Place a comma between the lines and skip it for each:

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

Jamey and user983965 are correct as your declaration is incorrect. However, foreach is not necessary here. If you simply correct the array declaration as follows, 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 } 
+6
source

You tried:

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

If you also get an array of computers from the active directory - like this:

$ computers = Get-ADComputer -filter {whatever}

Make sure you remember to select / expand the results .. like this:

$ Computers = Get-ADComputer -filter * | Object Selection -ExpandProperty Name

Then...

Invoke-Command -ComputerName $ Computers -ScriptBlock {Do Stuff}

0
source

Source: https://habr.com/ru/post/912885/


All Articles