3.8. Grouping Objects

Dealing with many objects often involves classifying them into several groups. PowerShell makes that very easy to do with its Group-Object cmdlet. The simplest and most common scenario is to split a collection into groups according to a property value. Here is how we can get a report of all services split into groups according to their status:

PS> Get-Service | Group-Object Status

Count Name                      Group
----- ----                      -----
   73 Running                   {AeLookupSvc, Appinfo, AudioEndpointBuil...
   79 Stopped                   {ALG, AppMgmt, aspnet_state, Browser...}

The result is a collection of GroupInfo objects. We can get each of them and query it for the actual objects that belong to the group by accessing the GroupInfo Group property:

PS> (Get-Service | Group-Object ...

Get Pro Windows PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.