0
0
PowerShellscripting~5 mins

Group-Object for categorization in PowerShell

Choose your learning style9 modes available
Introduction

Grouping objects helps organize data by shared properties. It makes it easier to see categories and count items in each group.

You want to count how many files have the same extension in a folder.
You need to organize a list of users by their department.
You want to group services by their status to check which are running or stopped.
You want to summarize sales data by product category.
Syntax
PowerShell
Get-Command | Group-Object -Property PropertyName

Get-Command is an example command that outputs objects.

-Property specifies the property to group by.

Examples
Groups services by their status.
PowerShell
Get-Service | Group-Object -Property Status
Groups files by their file extension.
PowerShell
Get-ChildItem | Group-Object -Property Extension
Groups a list of users by their department.
PowerShell
$users = @(
  [PSCustomObject]@{Name='Alice'; Dept='HR'},
  [PSCustomObject]@{Name='Bob'; Dept='IT'},
  [PSCustomObject]@{Name='Carol'; Dept='HR'}
)
$users | Group-Object -Property Dept
Sample Program

This script creates a list of files with extensions, groups them by extension, and prints each extension with how many files have it.

PowerShell
$files = @(
  [PSCustomObject]@{Name='file1.txt'; Extension='.txt'},
  [PSCustomObject]@{Name='file2.doc'; Extension='.doc'},
  [PSCustomObject]@{Name='file3.txt'; Extension='.txt'},
  [PSCustomObject]@{Name='file4.pdf'; Extension='.pdf'}
)

$grouped = $files | Group-Object -Property Extension

foreach ($group in $grouped) {
  Write-Output "Extension: $($group.Name) - Count: $($group.Count)"
}
OutputSuccess
Important Notes

Group-Object outputs groups with properties: Name (group key), Count (number of items), and Group (the items).

You can group by multiple properties by passing an array to -Property.

Summary

Group-Object helps organize data by shared property values.

It is useful to count or categorize items quickly.

Output groups include the group name, count, and the grouped items.