PowerShell 2.0: One Cmdlet at a Time 34 Invoke-Commmand

Continuing the series looking at new cmdlets available in PowerShell 2.0. This time we look at the Invoke-Command cmdlet.

What can I do with it?

Run commands on local or remote computers and return the results.

Examples:

Establish a persistent remote PowerShell connection to Test01 using New-PSSession and store it in the variable $session. Then return the results for which services begin with T.

$session = New-PSSession -ComputerName Test01 Invoke-Command -Session $session -ScriptBlock {Get-Service | Where-Object {$_.name -like ‘T*’}}

You can see that the results contain a property PSComputerName that shows which server the results came from.

You don’t need to stretch your imagination too far to see how this could quickly become extremely powerful. Imagine instead that you used New-PSSession to make sessions to 100 servers stored in a csv file and run the same command to all of those servers. The change in the code would be very small.

$sessions = New-PSSession -ComputerName (Get-Content servers.csv) Invoke-Command -Session $sessions -ScriptBlock {Get-Service | Where-Object {$_.name -like ‘T*’}}

How could I have done this in PowerShell 1.0?

Remoting did not exist in PowerShell 1.0, you would have needed to use Remote Desktop to run an interactive session on a remote server.

1000 things 1% better!