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:


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)
  elseif ($_.Length -gt 10KB)

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


Twitter This Tip! ReTweet this Tip!