🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Grouping Data

Grouping data is putting items that share a value into one group. It lets you count how many items share each value.

Group items by a property

Group the items by Kind. Each line prints the shared value and how many items share it.

$items = @(
  [PSCustomObject]@{Kind='fruit'; Name='apple'}
  [PSCustomObject]@{Kind='fruit'; Name='pear'}
  [PSCustomObject]@{Kind='veg'; Name='carrot'}
)
$groups = $items | Group-Object Kind
foreach ($g in $groups) { $g.Name + ': ' + $g.Count }

Group plain values

Group-Object also groups plain values by the value itself. Each line again prints the value and its count.

$words = @('red', 'blue', 'red')
$groups = $words | Group-Object
foreach ($g in $groups) { $g.Name + ': ' + $g.Count }

Keep only names and counts

Add -NoElement when you only need the counts. The items are not kept, so only names and counts remain.

$items = @(
  [PSCustomObject]@{Type='book'; Title='Atlas'}
  [PSCustomObject]@{Type='book'; Title='Maps'}
  [PSCustomObject]@{Type='game'; Title='Chess'}
)
$groups = $items | Group-Object Type -NoElement
foreach ($g in $groups) { $g.Name + ': ' + $g.Count }

Example

$items = @(
  [PSCustomObject]@{Kind='fruit'; Name='apple'}
  [PSCustomObject]@{Kind='fruit'; Name='pear'}
  [PSCustomObject]@{Kind='veg'; Name='carrot'}
)
$groups = $items | Group-Object Kind
foreach ($g in $groups) { $g.Name + ': ' + $g.Count }
'Counts only:'
$counts = $items | Group-Object Kind -NoElement
foreach ($g in $counts) { $g.Name + ': ' + $g.Count }

Key points

  • Group-Object: a command that puts items sharing a value into groups.
  • Use Group-Object followed by a property name to group by that property.
  • Each group has a Name, which is the shared value.
  • Each group has a Count, which is the number of items in the group.
  • Use -NoElement with Group-Object to keep only names and counts.

In this example, the script groups the items by Kind and prints each name and count, then groups the same items with -NoElement and prints the same names and counts without keeping the items.

Note

print only Name and Count, because printing a whole group prints its items too.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which line groups items by Kind and keeps only the counts, not the items?