Separating Results by Property Value

by Dec 13, 2016

If you use PowerShell remoting to receive information from remote machines, you can use fan-out simply by specifying more than one computer name. PowerShell will then automagically contact all machines simultaneously, which saves a lot of time (all of this requires that you have set up and enabled PowerShell on the affected machines, of course, which is not covered here).

The results come back in random order because all contacted machines return their information to you when they are ready.

To separate result data again per computer, use Group-Object:

$pc1 = $env:computername
$pc2 = '192.168.2.112'

$code = 
{
  Get-Service | Where-Object Status -eq Running
}

# get all results
$result = Invoke-Command -ScriptBlock $code -ComputerName $pc1, $pc2 

# separate per computer
$groups = $result | Group-Object -Property PSComputerName -AsHashTable 
$groups

# access per computer results separately
$groups.$pc1
$groups.$pc2

When you specify -AsHashTable, Group-Object creates a hash table and uses the computer name as key. This way, you can use the time-saving parallel processing and still consume results per computer.

Twitter This Tip! ReTweet this Tip!