Scripting PowerShell Group-Object Cmdlet

Introduction to Scripting PowerShell Group-Object

GUIs such as Task Manager lack the ability to group columns or objects.  Hence, one of the benefits of using a PowerShell script is that you can append a Group-Object clause, and thus get a more meaningful display of data.  I have also included the Format-Table -GroupBy parameter, which is an alternative technique to the Group-Object cmdlet.

PowerShell Group-Object Topics

 ♣

Example 1: Group Processes

# PowerShell Group Example
Clear-Host
Get-Process | Group-Object company
# Compared with:
Get-Process | Group-Object company | Sort-Object count -descending

While I favour the full command (above), you can omit ‘-object’ from Group-Object (or Sort-Object.  This shortened version (below) will work:

Get-Process | group company | Sort count -descending.

-GroupBy Alternative to Group-Object

Here is a parallel technique, which achieves a slightly different result by using Format-Table and its parameter -GroupBy:

# PowerShell -GroupBy Example
Clear-Host
Get-Process | Sort-Object company |
Format-Table Name, Company -GroupBy Company -auto

Note 1: You don't need the backtick (`) to word-wrap to the next line, if you end the line with a pipe (|).

Guy Recommends: Free WMI Monitor for PowerShellSolarwinds Free WMI Monitor for PowerShell

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory, or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

Example 2:  Service, Sorting on Two Criteria

This Group-Object example employs Get-Service as a vehicle for testing this PowerShell cmdlet.

Once we have grouped objects, we can add clarity by appending extra code which sorts the items into numeric or alphabetical order.  Observe in the following examples how PowerShell provides Sort-Object for sequencing the output.

# Preliminary Group

# Preliminary Group Example
Clear-Host
Get-Service | Group-Object status
#Compared with
Get-Service | Group-Object status | Format-List

Again, here is an alternative technique employing Format-Table with -GroupBy to enhance the output.  With Format-Table you can refine the output by specifying the properties.

# Main Event: Sort-Object

# Sort and Group on Two Criteria
Get-Service | Sort-Object status, name |
 Format-Table -GroupBy status

 

# Compared with
Clear-Host
Get-Service | sort status, name |
Ft -GroupBy status Name, DisplayName, Status -auto

Note 2:  These examples sort firstly on ‘status’, then secondly on ‘name’.

Note 3:  Ft is an alias for Format-Table.

Another (Better) Example Using -ExpandProperty

My point is that typically of Microsoft, PowerShell offers at least 3 alternatives to achieve the same outcome.

Get-Service | Group-Object status | select -ExpandProperty group

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Network Performance Monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Example 3: Group Eventlog

This pair of scripts compares the Group-Object cmdlet with the -GroupBy parameter.

Example 3a  Group-Object
The purpose of this script is to find the most common log messages.

# PowerShell Group-Object and Sort
Clear-Host
Get-Eventlog system -newest 3000 |
Group-Object eventid |
Sort-Object Count -descending | Format-Table Count, Name -autosize

Note 4: With Get-Eventlog, always remember the name of that log!  For example, System, Application, Security or which ever log you are investigating.

Example 3b -GroupBy
The purpose of this script is to find the most common error messages and group them.

# PowerShell Sort-Object then -GroupBy
Clear-Host
Get-Eventlog system -newest 3000 | Sort-Object eventid |
Where {$_.EntryType -eq "Error"} | Format-Table -GroupBy eventid

Note 5: Until I knew better I used the backtick (`) at the end of line 2.  I now realize we can avoid this tiny symbol if you end the line with a (|).  Compare and contrast with example 3a.

Another example of -GroupBy

Guy Recommends:  SolarWinds’ Log & Event Management ToolSolarwinds Log and Event Management Tool

LEM will alert you to problems such as when a key application on a particular server is unavailable.  It can also detect when services have stopped, or if there is a network latency problem.  Perhaps this log and event management tool’s most interesting ability is to take corrective action, for example by restarting services, or isolating the source of a maleware attack.

Yet perhaps the killer reason why people use LEM is for its compliance capability, with a little help from you, it will ensure that your organization complies with industry standards such as CISP or FERPA.  LEM is a really smart application that can make correlations between data in different logs, then use its built-in logic to take corrective action, to restart services, or thwart potential security breaches – give LEM a whirl.

Download your FREE trial of SolarWinds Log & Event Management tool.

Research Group-Object Parameters

Sometimes we get carried away and forget the basics.  In the case of PowerShell this means remembering ‘help’ with the -full parameter.  Thus in this instance we need:

# Group-Object Parameters
Clear-Host
Get-Help Group-Object -full

Just when I thought this PowerShell cmdlet has no interesting parameters, I discovered Group-Object’s -AsHashTable, see more details here.

Find More PowerShell ‘Object’ Cmdlets

Clear-Host
Get-Command -Noun object

As a result of this knowledge you can refine the output of a where clause by piping it into a Sort-Object statement.

Summary of PowerShell’s Group-Object Cmdlet

Group-Object is a useful addition to your PowerShell tool-kit, indeed the ability to control data output is a one reason for employing PowerShell rather than using the GUIs. A typical scenario for Group-Object is where you wish to aggregate the data displayed by a PowerShell query. As usual, you are spoilt for choice, the decision lies between piping to Group-Object, or alternatively to experiment with Format-Table -GroupBy.

If you like this page then please share it with your friends

 


See more PowerShell examples for syntax

PowerShell Home  • Syntax  • ISE (GUI)  • Pipeline  • Format-Table  • Select-Object

Compare-Object  • Compare-Object (Registry)  • Group-Object  • Sort-Object  • Foreach

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.