TExcelTAD
Home › PowerShell › PowerShell Group & Measure

PowerShell Group & Measure

Once you can filter and sort, the next step is summarising: how many orders per country, what is the total size of these files, which value appears most often. Group-Object and Measure-Object answer these questions, and Compare-Object shows the differences between two lists.

Measure-Object

Measure-Object (alias measure) counts objects and calculates statistics on a property:

powershell · try it yourself
$orders = @(
    [pscustomobject]@{ Id = 1; Country = 'NO'; Amount = 120.5 }
    [pscustomobject]@{ Id = 2; Country = 'SE'; Amount = 80 }
    [pscustomobject]@{ Id = 3; Country = 'NO'; Amount = 45.25 }
    [pscustomobject]@{ Id = 4; Country = 'DK'; Amount = 300 }
    [pscustomobject]@{ Id = 5; Country = 'SE'; Amount = 19.75 }
)

$stats = $orders | Measure-Object -Property Amount -Sum -Average -Minimum -Maximum
$stats.Count
$stats.Sum
$stats.Average
"min $($stats.Minimum), max $($stats.Maximum)"
($orders | Measure-Object Amount -AllStats).StandardDeviation.ToString('0.00')
5
565.5
113.1
min 19.75, max 300
111.13

For text, -Line, -Word and -Character count like the Unix wc command:

powershell · try it yourself
$poem = @"
Objects flow through pipes
each one carries its own shape
no parsing needed
"@
$poem | Measure-Object -Line -Word -Character | Format-List Lines, Words, Characters

Lines      : 3
Words      : 13
Characters : 75

Group-Object

Group-Object (alias group) collects objects with the same property value into groups. Each group has a Name (the shared value), a Count and the Group itself (the original objects):

powershell · try it yourself
$orders = @(
    [pscustomobject]@{ Id = 1; Country = 'NO'; Amount = 120.5 }
    [pscustomobject]@{ Id = 2; Country = 'SE'; Amount = 80 }
    [pscustomobject]@{ Id = 3; Country = 'NO'; Amount = 45.25 }
    [pscustomobject]@{ Id = 4; Country = 'DK'; Amount = 300 }
    [pscustomobject]@{ Id = 5; Country = 'SE'; Amount = 19.75 }
)

$orders | Group-Object Country | Sort-Object Name | Format-Table Count, Name

foreach ($g in $orders | Group-Object Country | Sort-Object Name) {
    $total = ($g.Group | Measure-Object Amount -Sum).Sum
    '{0}: {1} orders, total {2:N2}' -f $g.Name, $g.Count, $total
}

Count Name
----- ----
    1 DK
    2 NO
    2 SE

DK: 1 orders, total 300.00
NO: 2 orders, total 165.75
SE: 2 orders, total 99.75

Combining Group-Object with Measure-Object on each group gives you the equivalent of SQL's GROUP BY … SUM().

Grouping options

powershell · try it yourself
$words = 'apple', 'avocado', 'banana', 'blueberry', 'cherry', 'apricot'

# Group by a calculated value
$words | Group-Object { $_[0] } | ForEach-Object { "$($_.Name): $($_.Group -join ', ')" }

# A lookup table: group name -> objects
$byLength = $words | Group-Object Length -AsHashTable
$byLength[6] -join ', '

# Only the counts
$words | Group-Object { $_.Length -gt 6 } -NoElement | ForEach-Object { "long=$($_.Name): $($_.Count)" }
a: apple, avocado, apricot
b: banana, blueberry
c: cherry
banana, cherry
long=False: 3
long=True: 3

-AsHashTable returns a hashtable keyed by the group value, perfect for fast lookups later. -NoElement drops the Group property when you only need counts.

Most frequent values

A classic one-liner: group, sort by count, take the top entries.

powershell · try it yourself
$log = @'
GET /index.html 200
GET /about.html 200
POST /login 401
GET /index.html 200
GET /missing 404
POST /login 200
GET /index.html 304
'@ -split "`n"

$log | ForEach-Object { ($_ -split ' ')[1] } |
    Group-Object |
    Sort-Object Count, Name -Descending |
    Select-Object -First 2 Count, Name

Count Name
----- ----
    3 /index.html
    2 /login

Compare-Object

Compare-Object shows what differs between two collections. <= means "only in the reference (first) set", => "only in the difference (second) set":

powershell · try it yourself
$expected = 'nginx', 'postgres', 'redis', 'cron'
$running  = 'nginx', 'redis', 'sshd'

Compare-Object -ReferenceObject $expected -DifferenceObject $running |
    ForEach-Object { '{0} {1}' -f $_.SideIndicator, $_.InputObject }

'---'
Compare-Object $expected $running -IncludeEqual -ExcludeDifferent | ForEach-Object InputObject
=> sshd
<= postgres
<= cron
---
nginx
redis

This is great for checks like "which expected services aren't running" or "which users are new since yesterday's export".

Test yourself

Which property of a Group-Object result holds the original objects?

  1. Name
  2. Count
  3. Group
  4. Values

How do you get the total of the Size property of $files?

  1. $files | Group-Object Size
  2. ($files | Measure-Object Size -Sum).Sum
  3. $files.Size.Total
  4. Sum-Object $files

In Compare-Object output, what does => mean?

  1. The item is in both sets
  2. The item exists only in the difference (second) set
  3. The item exists only in the reference (first) set
  4. The items are equal