Loading
0x40Lesson 5 of 17

The object pipeline

Filter, sort, select, measure and group objects with the core pipeline cmdlets.

30 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • Pass objects through a pipeline and refer to the current one as $_
  • Use Where-Object, Sort-Object, Select-Object and ForEach-Object
  • Summarize objects with Measure-Object and Group-Object

The pipeline, |, hands each object a command outputs to the next command, one at a time. Because the objects keep their properties all the way along, a handful of general-purpose cmdlets cover almost every reporting job:

CmdletDoesAlias
Where-Objectkeeps objects that pass a testwhere, ?
Sort-Objectsorts by one or more properties (-Descending, -Unique)sort
Select-Objectpicks properties, or the first/last N objectsselect
ForEach-Objectruns code for each objectforeach, %
Measure-Objectcounts, and sums/averages/min/max a propertymeasure
Group-Objectgroups objects with the same valuegroup

Inside a script block, $_ (also spelled $PSItem) is the object currently passing through.

pipeline.ps1
1$dragons = @'
2Name,Species,Wingspan,Temperament
3Ember,Firedrake,12,grumpy
4Glim,Wisp,2,playful
5Skyla,Stormwing,15,proud
6Thornjaw,Wyrm,6,grumpy
7'@ | ConvertFrom-Csv
8
9$dragons | Where-Object { $_.Temperament -eq 'grumpy' } | ForEach-Object { $_.Name }
10$dragons | Sort-Object { [int]$_.Wingspan } -Descending | Select-Object -First 1 -ExpandProperty Name
11$dragons | ForEach-Object { '{0} the {1}' -f $_.Name, $_.Species.ToLower() } | Select-Object -Last 2
12($dragons | Measure-Object -Property Wingspan -Sum -Maximum).Sum
Output
Ember
Thornjaw
Skyla
Skyla the stormwing
Thornjaw the wyrm
35

ConvertFrom-Csv turned the CSV text into four objects - you’ll meet it properly two lessons from now. Two shortcuts are worth knowing:

  • Simplified syntax for simple tests: Where-Object Temperament -eq grumpy means the same as the script-block form. Use braces as soon as you need more than one comparison.
  • Member names in ForEach-Object: ForEach-Object Name outputs each object’s Name. So does Select-Object -ExpandProperty Name. (Plain Select-Object Name keeps objects that have only a Name property - it prints a table, not bare strings.)

Try it

Object pipeline lab

Here are all eight sanctuary dragons as objects in $dragons. Click cmdlets to build a pipeline and watch the objects after every stage. Match each challenge’s target.

Try putting Select-Object Name before a sort or filter - what goes wrong?

Solved 0/7

Challenge 1: How many grumpy dragons are there?

PS> $dragons

Click a cmdlet to add it to the end of the pipeline:

$dragons8 objects
NameSpeciesWingspanTemperamentAge
EmberFiredrake12grumpy140
MossbackWyrm4sleepy310
CinderFiredrake9playful35
GlimWisp2playful12
ThornjawWyrm6grumpy205
SkylaStormwing15proud88
PebbleWyrm3playful7
VesperStormwing11grumpy150
Target result
Count
3

Filter left, format right

Two rules of thumb keep pipelines fast and correct:

  • Filter left: drop unwanted objects as early as possible - ideally with the first command’s own parameters (Get-ChildItem -Filter *.log beats Get-ChildItem | Where-Object Name -like *.log).
  • Format right: Format-Table and Format-List turn objects into display instructions, so nothing useful can come after them. Put them last, or not at all.

Key takeaways

  • The pipeline passes objects one by one; $_ is the current one.

  • Where-Object filters, Sort-Object sorts, Select-Object picks, ForEach-Object transforms.

  • Measure-Object counts and totals; Group-Object counts by value.

  • Filter left, format right - and convert text to numbers before sorting or comparing.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write PowerShell scripts

Write a script in the editor and run it for real against sample input, which is piped into your script as $input. Scripts run on PowerShell 6.2 through Try It Online (tio.run), a free public service, so these exercises avoid PowerShell 7-only syntax; your script and test input are sent there.

Exercise 1

Grumpy giants

+25 XP

The input is the dragon roster as CSV (with a header row). The starter turns it into objects. Print the names of the grumpy dragons, largest wingspan first. Careful: CSV values are text!

  • The residents
  • The visitors
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Exercise 2

Species census

+25 XP

The input is the dragon roster as CSV. Print one line per species with its count, in alphabetical order (Firedrake: 2), then a last line naming the most common species: Most common: Wyrm (3).

  • The residents
  • The visitors plus one
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Did you like the lesson? 😆👍
Consider a donation to support our work: