DEV Community

Cover image for Count Things in PowerShell: Group-Object Explained
arnostorg
arnostorg

Posted on Edited on

Count Things in PowerShell: Group-Object Explained

"How many PDFs are in that share?" "Which error code shows up most in last night's log?" "How much of this folder is spreadsheets?" All three are the same question: count things by a property. In PowerShell, the answer is Group-Object. You give it objects and a property, and it gives you one row per distinct value with a Count.

This tip walks through the jobs you will actually use it for: counting files by extension, getting a clean count-only table, grouping by a calculated value like year or size, counting error codes in a log, summing sizes per group, and looking things up fast with a hash table. Every snippet was run in PowerShell 7.4, and the output shown is the real output. If you want to try the pipelines as you read, you can practice PowerShell pipeline commands in a free browser terminal with CMD Master.

Set up a safe demo folder

Run this first. It creates a throwaway folder in your temp directory with ten small files (fixed sizes and dates) and a short log, so your counts match mine:

$demo = Join-Path ([IO.Path]::GetTempPath()) 'group-object-demo'
New-Item -ItemType Directory -Path (Join-Path $demo 'Logs') -Force | Out-Null
Set-Location -Path $demo

# Name = size in bytes, date (LastWriteTime)
$files = @(
    @('report-2024.xlsx', 5000,  '2024-03-10'), @('report-2025.xlsx', 6200, '2025-02-14'),
    @('invoice-01.pdf',   2400,  '2025-06-01'), @('invoice-02.pdf',   3100, '2026-02-01'),
    @('SCAN-03.PDF',      1800,  '2026-03-01'), @('notes.txt',         300, '2024-11-11'),
    @('todo.txt',          120,  '2026-04-01'), @('readme.txt',        900, '2025-09-09'),
    @('draft.txt',          50,  '2025-12-01'), @('photo.jpg',       48000, '2024-07-07')
)
foreach ($f in $files) {
    Set-Content -Path $f[0] -Value ('x' * $f[1]) -NoNewline
    (Get-Item -Path $f[0]).LastWriteTime = $f[2]
}

@'
2026-11-28 08:01:12 INFO  service started
2026-11-28 08:02:40 ERROR E1001 disk quota exceeded
2026-11-28 08:05:03 WARN  slow response 2300 ms
2026-11-28 08:07:19 ERROR E2002 login failed for svc-backup
2026-11-28 08:09:55 ERROR E1001 disk quota exceeded
2026-11-28 08:12:31 INFO  job 41 finished
2026-11-28 08:15:47 ERROR E3003 timeout calling api.internal
2026-11-28 08:18:02 ERROR E1001 disk quota exceeded
2026-11-28 08:20:44 WARN  retrying job 42
2026-11-28 08:22:10 ERROR E2002 login failed for svc-backup
'@ | Set-Content -Path .\Logs\app.log

Get-ChildItem -File |
    Select-Object -Property Name, Length,
        @{ Name = 'Modified'; Expression = { $_.LastWriteTime.ToString('yyyy-MM-dd') } }
Enter fullscreen mode Exit fullscreen mode
Name             Length Modified
----             ------ --------
draft.txt            50 2025-12-01
invoice-01.pdf     2400 2025-06-01
invoice-02.pdf     3100 2026-02-01
notes.txt           300 2024-11-11
photo.jpg         48000 2024-07-07
readme.txt          900 2025-09-09
report-2024.xlsx   5000 2024-03-10
report-2025.xlsx   6200 2025-02-14
SCAN-03.PDF        1800 2026-03-01
todo.txt            120 2026-04-01
Enter fullscreen mode Exit fullscreen mode

All the later snippets assume you are still inside that folder.

Job 1: Count files by extension

This is the one-liner most people come for. Group by Extension, then sort so the biggest group is on top:

Get-ChildItem -File |
    Group-Object -Property Extension |
    Sort-Object -Property Count -Descending
Enter fullscreen mode Exit fullscreen mode
Count Name                      Group
----- ----                      -----
    4 .txt                      {/workspace/devto-group-object/sandbox/group-o…
    3 .pdf                      {/workspace/devto-group-object/sandbox/group-o…
    2 .xlsx                     {/workspace/devto-group-object/sandbox/group-o…
    1 .jpg                      {/workspace/devto-group-object/sandbox/group-o…
Enter fullscreen mode Exit fullscreen mode

Each row is a GroupInfo object with three useful properties:

  • Count: how many objects landed in the group.
  • Name: the value they share (here, the extension).
  • Group: the original objects themselves. The table shows them as full paths. I ran this on Linux, so you see a Linux temp path; on Windows you will see something like C:\Users\you\AppData\Local\Temp\group-object-demo\....

Notice that .pdf has 3 files even though one of them is SCAN-03.PDF. Grouping ignores case by default. More on that below.

Job 2: Just the counts (-NoElement)

Most of the time you only want the numbers. -NoElement drops the Group column, so the table is shorter and the output is lighter:

Get-ChildItem -File |
    Group-Object -Property Extension -NoElement |
    Sort-Object -Property Count -Descending
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    4 .txt
    3 .pdf
    2 .xlsx
    1 .jpg
Enter fullscreen mode Exit fullscreen mode

When you do need the files behind a count, keep the groups and read .Group:

$byExt = Get-ChildItem -File | Group-Object -Property Extension

$pdf = $byExt | Where-Object Name -eq '.pdf'
$pdf.Count
$pdf.Group.Name
Enter fullscreen mode Exit fullscreen mode
3
invoice-01.pdf
invoice-02.pdf
SCAN-03.PDF
Enter fullscreen mode Exit fullscreen mode

Job 3: Group by something that isn't a property (calculated groups)

-Property also accepts a script block. Whatever the block returns becomes the group name. Count files by the year they were last changed:

Get-ChildItem -File |
    Group-Object -Property { $_.LastWriteTime.Year } -NoElement
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    3 2024
    4 2025
    3 2026
Enter fullscreen mode Exit fullscreen mode

The same trick builds size buckets. The leading 1, 2, 3 are there on purpose: Group-Object sorts its output by name, so numbering the labels keeps the buckets in a sensible order:

Get-ChildItem -File |
    Group-Object -Property {
        if     ($_.Length -lt 1KB)  { '1 Small (< 1 KB)' }
        elseif ($_.Length -lt 10KB) { '2 Medium (1-10 KB)' }
        else                        { '3 Large (10 KB+)' }
    } -NoElement
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    4 1 Small (< 1 KB)
    5 2 Medium (1-10 KB)
    1 3 Large (10 KB+)
Enter fullscreen mode Exit fullscreen mode

Calculated properties work the same way they do in Select-Object and Sort-Object. The about_Calculated_Properties page has the full syntax.

Job 4: Count error codes in a log file

Log lines are just strings, so pull out the part you want to count, then group the strings. Here Select-String finds the error lines and -replace keeps only the code:

Select-String -Path .\Logs\app.log -Pattern 'ERROR E\d+' |
    ForEach-Object { $_.Line -replace '^.*ERROR (E\d+).*$', '$1' } |
    Group-Object -NoElement |
    Sort-Object -Property Count -Descending
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    3 E1001
    2 E2002
    1 E3003
Enter fullscreen mode Exit fullscreen mode

With no -Property, Group-Object groups the strings by their own value. The same idea gives you a quick count per log level. Split each line on whitespace and take the third field:

Get-Content -Path .\Logs\app.log |
    ForEach-Object { ($_ -split '\s+')[2] } |
    Group-Object -NoElement
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    6 ERROR
    2 INFO
    2 WARN
Enter fullscreen mode Exit fullscreen mode

That is a decent "what happened overnight" summary in four lines. See the Select-String reference for -Pattern, -Context and friends.

Job 5: Sum sizes per group (Group-Object + Measure-Object)

Counting files is good. Knowing which type eats the space is better. Loop over the groups and run Measure-Object on each .Group:

Get-ChildItem -File |
    Group-Object -Property Extension |
    ForEach-Object {
        $size = $_.Group | Measure-Object -Property Length -Sum
        [pscustomobject]@{
            Extension = $_.Name
            Files     = $_.Count
            TotalKB   = [math]::Round($size.Sum / 1KB, 1)
        }
    } |
    Sort-Object -Property TotalKB -Descending
Enter fullscreen mode Exit fullscreen mode
Extension Files TotalKB
--------- ----- -------
.jpg          1   46.90
.xlsx         2   10.90
.pdf          3    7.10
.txt          4    1.30
Enter fullscreen mode Exit fullscreen mode

One photo outweighs everything else combined. That is the kind of answer that makes a cleanup decision easy.

Job 6: Group by two properties (and what Name looks like)

Pass more than one property and you get one group per combination. The Name becomes the values joined with a comma and a space:

Get-ChildItem -File |
    Group-Object -Property Extension, { $_.LastWriteTime.Year } -NoElement
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    1 .jpg, 2024
    1 .pdf, 2025
    2 .pdf, 2026
    1 .txt, 2024
    2 .txt, 2025
    1 .txt, 2026
    1 .xlsx, 2024
    1 .xlsx, 2025
Enter fullscreen mode Exit fullscreen mode

Because Name is just a string like .pdf, 2026, don't try to split it to get the parts back. Use the Values property instead. It holds the individual values in order, so Values[1] is the year:

Get-ChildItem -File |
    Group-Object -Property Extension, { $_.LastWriteTime.Year } |
    Where-Object { $_.Values[1] -eq 2026 } |
    Select-Object -Property Count, Name, @{ Name = 'Files'; Expression = { $_.Group.Name -join ', ' } }
Enter fullscreen mode Exit fullscreen mode
Count Name       Files
----- ----       -----
    2 .pdf, 2026 invoice-02.pdf, SCAN-03.PDF
    1 .txt, 2026 todo.txt
Enter fullscreen mode Exit fullscreen mode

Job 7: Fast lookups with -AsHashTable

If you are going to look groups up by name later in a script, ask for a hash table instead of a list. Keys are the group values and each value is the group's objects:

$byExt = Get-ChildItem -File | Group-Object -Property Extension -AsHashTable

$byExt['.txt'].Name
$byExt.'.xlsx'.Count
Enter fullscreen mode Exit fullscreen mode
draft.txt
notes.txt
readme.txt
todo.txt
2
Enter fullscreen mode Exit fullscreen mode

The -AsString gotcha

By default, the keys keep the type of the grouped value. That's fine for Extension (a string), but a calculated year is an Int32, and a string key won't find it:

$byYear = Get-ChildItem -File | Group-Object -Property { $_.LastWriteTime.Year } -AsHashTable

"Key type: $(($byYear.Keys | Select-Object -First 1).GetType().Name)"
"By string '2025': $($byYear['2025'].Count) files"
"By number  2025 : $($byYear[2025].Count) files"

$byYearText = Get-ChildItem -File | Group-Object -Property { $_.LastWriteTime.Year } -AsHashTable -AsString
"With -AsString, '2025': $($byYearText['2025'].Count) files"
Enter fullscreen mode Exit fullscreen mode
Key type: Int32
By string '2025': 0 files
By number  2025 : 4 files
With -AsString, '2025': 4 files
Enter fullscreen mode Exit fullscreen mode

No error, just an empty result. If you plan to look up keys by text (from user input, a CSV or a config file), add -AsString. The Group-Object docs describe it this way: "By default, the hash table keys are instances of the grouped object."

Case sensitivity (-CaseSensitive)

Group-Object ignores case unless you tell it otherwise. That's why .pdf and .PDF landed in one group earlier. Add -CaseSensitive to split them:

Get-ChildItem -File -Filter *.pdf |
    Group-Object -Property Extension -CaseSensitive -NoElement
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    2 .pdf
    1 .PDF
Enter fullscreen mode Exit fullscreen mode

The same switch also matters for hash tables. Since PowerShell 7, combining -CaseSensitive with -AsHashTable gives you a hash table with case-sensitive keys:

$plain = Get-ChildItem -File -Filter *.pdf | Group-Object -Property Extension -AsHashTable
$exact = Get-ChildItem -File -Filter *.pdf | Group-Object -Property Extension -AsHashTable -CaseSensitive

"Default keys:        $($plain.Keys -join ', ')"
"-CaseSensitive keys: $(($exact.Keys | Sort-Object) -join ', ')"
"`$exact['.PDF'] has $($exact['.PDF'].Count) file(s)"
Enter fullscreen mode Exit fullscreen mode
Default keys:        .pdf
-CaseSensitive keys: .PDF, .pdf
$exact['.PDF'] has 1 file(s)
Enter fullscreen mode Exit fullscreen mode

Common gotchas

1. Exporting groups straight to CSV. The Group column is a collection, and CSV can only hold text, so you get type names instead of data:

Get-ChildItem -File |
    Group-Object -Property Extension |
    Export-Csv -Path .\Logs\by-extension.csv

Get-Content -Path .\Logs\by-extension.csv -TotalCount 3
Enter fullscreen mode Exit fullscreen mode
"Values","Count","Group","Name"
"System.Collections.ArrayList","1","System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]",".jpg"
"System.Collections.ArrayList","3","System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]",".pdf"
Enter fullscreen mode Exit fullscreen mode

Fix it with -NoElement and pick the columns you want:

Get-ChildItem -File |
    Group-Object -Property Extension -NoElement |
    Select-Object -Property Name, Count |
    Export-Csv -Path .\Logs\by-extension.csv

Get-Content -Path .\Logs\by-extension.csv
Enter fullscreen mode Exit fullscreen mode
"Name","Count"
".jpg","1"
".pdf","3"
".txt","4"
".xlsx","2"
Enter fullscreen mode Exit fullscreen mode

2. Using -InputObject instead of the pipeline. -InputObject treats the whole array as one object, so you get a single group with a count of 1. Pipe the collection instead:

$files = Get-ChildItem -File

# One group with one member: the whole array
Group-Object -InputObject $files -Property Extension -NoElement

# What you meant: pipe it
$files | Group-Object -Property Extension -NoElement
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    1
    1 .jpg
    3 .pdf
    4 .txt
    2 .xlsx
Enter fullscreen mode Exit fullscreen mode

The first line of output is the whole array as one group with an empty name. The rest is what you wanted.

3. Name is always a string. Group numbers and then sort by Name, and you get text order, where 10 and 120 come before 9. Sort by the number instead:

$sizes = 9, 10, 9, 120, 10, 9

$sizes | Group-Object -NoElement | Sort-Object -Property Name
'---'
$sizes | Group-Object -NoElement | Sort-Object -Property { [int]$_.Name }
Enter fullscreen mode Exit fullscreen mode
Count Name
----- ----
    2 10
    1 120
    3 9
---
    3 9
    2 10
    1 120
Enter fullscreen mode Exit fullscreen mode

4. Groups come out sorted by name, not by count. If you want "most common first", you have to add Sort-Object -Property Count -Descending yourself, as in Job 1. The Sort-Object reference covers multi-key sorts.

Quick reference

You want Use
Count per value, biggest first Group-Object Prop -NoElement, then Sort-Object Count -Descending
The objects behind a count The .Group property of that group
Group by a computed value Group-Object { $_.LastWriteTime.Year }
Total size per group Measure-Object Length -Sum on each $_.Group
Look up groups by key -AsHashTable -AsString
Treat .pdf and .PDF as different -CaseSensitive
Parts of a multi-property group $_.Values[0], $_.Values[1]

Practice it hands-on

Grouping clicks once you have tried it on your own data a few times. If you'd like a safe place to experiment first, CMD Master has interactive PowerShell lessons in a free browser terminal, plus CMD and Bash.

Your turn: what does this output?

No -CaseSensitive, no sorting. What exactly does this print, including the spelling of each Name?

'b', 'A', 'a', 'B', 'a' | Group-Object -NoElement
Enter fullscreen mode Exit fullscreen mode

Post your answer in the comments before you run it. The counts are the easy part; the interesting part is which letter case each group's Name shows, and why. I'll reply with the real output and the rule behind it.

Top comments (0)