Group-Object

Exploring PowerShell’s Group-Object Cmdlet

Welcome back to Wahmans PowerShell blog! Today we’re diving into a powerful yet often underused cmdlet: Group-Object. According to Microsoft, this cmdlet “groups objects that contain the same value for specified properties.” Think of it as a way to summarize and categorize your data quickly and efficiently right in PowerShell.

Whether you’re a PowerShell novice or a seasoned scripter, Group-Object can be a valuable addition to your toolbox. Let’s take a look at what it can do, progressing from basic to more advanced examples.

Example 1: Grouping an Array of Strings

$colors = @("Red", "Blue", "Red", "Green", "Blue", "Red")
$colors | Group-Object

Output: This will display how many times each color appears in the list. It’s a perfect beginner example to understand how grouping works with simple data types.

Example 2: Grouping Processes by Name

Get-Process | Group-Object -Property ProcessName

Output: This will group all running processes by their name and show a count of how many instances are running for each. Super handy when you’re tracking down rogue or excessive processes.

Example 3: Grouping Files by Extension

Get-ChildItem -Path "C:\Users\Public\Documents" -Recurse |
    Where-Object { -not $_.PSIsContainer } |
    Group-Object -Property Extension

Output: This will show how many files of each type (extension) exist under the specified folder. Great for file management or organizing backups.

Example 4: Grouping and Saving Results to a CSV

$groupedUsers = Get-ADUser -Filter * -Property Department |
    Group-Object -Property Department

$groupedUsers | ForEach-Object {
    [PSCustomObject]@{
        Department = $_.Name
        UserCount = $_.Count
    }
} | Export-Csv -Path "C:\Reports\DepartmentUserCounts.csv" -NoTypeInformation

Output: In this more advanced scenario, we retrieve AD users, group them by department, and export the grouped count to a CSV. Perfect for reporting and automation scenarios.

Final Thoughts

Group-Object is a deceptively simple cmdlet that offers a lot of power for summarizing and reporting on both simple and complex data. Whether you’re cleaning up output, analyzing logs, or automating reports, it’s a must-have in your PowerShell toolkit.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *