Use Group-Object to Create Hash Tables

by Aug 12, 2014

All PowerShell versions

Group-Object can pile objects up, putting objects with the same property together in one pile.

This can be quite useful, especially when you ask Group-Object to return hash tables. This would generate a hash table with piles for all available service status modes:

$hash = Get-Service | 
  Group-Object -Property Status -AsHashTable -AsString

You could now get back the list of all running (or stopped) services like this:

$hash.Running
$hash.Stopped

Use any object property you want to create the piles. This example will pile up files in three piles: one for small, one for medium, and one for large files.

$code = 
{
  if ($_.Length -gt 1MB)
  {'huge'}
  elseif ($_.Length -gt 10KB)
  {'average'}
  else
  {'tiny'}
}

$hash = Get-ChildItem -Path c:\windows |
  Group-Object -Property $code -AsHashTable -AsString


#$hash.Tiny
$hash.Huge

Twitter This Tip! ReTweet this Tip!