Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 34 ยท Objects and the Pipeline

Where-Object, Select-Object and Sort-Object

Filter, reshape and sort objects in the PowerShell pipeline: Where-Object, Select-Object (-First, -Unique, calculated properties) and Sort-Object, with examples.

Most PowerShell commands return more than you want. Get-Process returns every process, Get-ChildItem every file, Get-Service every service. The skill that turns PowerShell from a list-printer into a tool is cutting that stream down: keep only the objects you care about, keep only the properties you care about, and put them in a useful order.

Three cmdlets do nearly all of that work. Where-Object filters objects, Select-Object picks properties (and the first or last few objects), and Sort-Object orders them. Because they work on objects rather than text, you never count columns or cut at character positions: you name properties. This lesson builds on the pipeline and objects and properties, and prepares the ground for grouping and measuring.

Real PowerShell cannot run on this page, so the PowerShell snippets are read-only. The runnable examples use a JavaScript stand-in: a tiny array pipeline with where, select and sort functions that behave like the cmdlets on the same sample data. It models the idea, not PowerShell itself, and it says so where the two differ.

Three jobs in the pipeline

Where-Object Keep objects that pass a test.
Select-Object Keep chosen properties or the first few objects.
Sort-Object Put objects in order by property.

Filter early, sort late, select last.

1 / 2

Where-Object: keep what passes a test

Where-Object reads each incoming object, runs a test, and passes the object on only when the test is true. The classic form uses a script block in braces, where $_ (also written $PSItem) is the current object:

POWERSHELL
Get-Service | Where-Object { $_.Status -eq 'Running' }
Get-Process | Where-Object { $_.CPU -gt 100 -and $_.Name -like 'c*' }

The comparison operators (-eq, -gt, -like, -match and friends) are covered in Operators and Comparison. Combine tests with -and, -or and -not.

When the test is a single comparison, there is a simplified syntax with no braces and no $_:

POWERSHELL
Get-Service | Where-Object Status -eq Running
Get-Process | Where-Object CPU -gt 100

Use the braces whenever you need more than one condition or a method call. Use the simplified form when it reads like a sentence. Aliases are where and ?, fine in a shell, but spell the full name in scripts you share.

There is also a method, .Where({ ... }), that works on any collection already in memory. It is a little faster for big in-memory arrays, but it does not stream from the pipeline, so Where-Object stays the everyday tool.

Filter left, format right

Where you filter matters for speed. This runs the whole listing first and then throws most of it away:

POWERSHELL
Get-ChildItem -Path C:\Logs -Recurse | Where-Object { $_.Extension -eq '.log' }

This asks the file system provider to do the filtering, so far fewer objects are ever created:

POWERSHELL
Get-ChildItem -Path C:\Logs -Recurse -Filter *.log

The rule of thumb is filter left: use the cmdlet's own parameters (-Filter, -Name, -Include, -Status) first, and Where-Object for whatever those cannot express. Its counterpart, covered in Formatting and Output, is format right: formatting goes last.

Select-Object: choose properties

Select-Object has two jobs. With -Property it builds new objects that carry only the properties you name:

POWERSHELL
Get-Process | Select-Object -Property Name, Id, WS

-Property is positional, so Select-Object Name, Id, WS is the same command. Wildcards work too: Select-Object Name, *Memory*.

Be aware that the result is a different kind of object. A Select-Object result has only the properties you picked, and (for objects that were not already plain data) its type name is changed, so methods of the original object are gone. Select at the end of a pipeline, when you are done calling methods.

-ExpandProperty: get the values themselves

Selecting one property still gives you objects with that one property, not the bare values. To unwrap the value, use -ExpandProperty:

POWERSHELL
Get-Process | Select-Object -Property Name | Select-Object -First 1     # an object with a Name property
Get-Process | Select-Object -ExpandProperty Name | Select-Object -First 1   # just a string

Use it when the next command needs plain strings or numbers, for example when feeding names into another cmdlet or a -join.

-First, -Last, -Skip and -Unique

Select-Object also trims the stream by position:

POWERSHELL
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5
Get-ChildItem | Select-Object -Last 3
Get-ChildItem | Select-Object -Skip 10 -First 10
'a','b','a','c' | Select-Object -Unique

-First has a bonus: once it has the objects it needs, PowerShell stops the upstream command, so Get-ChildItem -Recurse | Select-Object -First 1 does not have to walk the whole disk. -Last cannot stop early because it must see everything to know what the end is. -Unique compares whole values (or the selected properties) and keeps the first of each. Sort-Object has its own -Unique as well, shown below.

Calculated properties

A calculated property is a property you make up from a hashtable with two keys: a name and an expression. Inside the expression $_ is the current object.

POWERSHELL
Get-Process | Select-Object Name, @{ Name = 'MemoryMB'; Expression = { [math]::Round($_.WS / 1MB, 1) } }

The keys can be shortened: Name to N or Label, and Expression to E. Calculated properties are how you rename a column, change units, join two values or compute something that does not exist yet. Remember that @{ ... } here is a hashtable, which you will meet properly in Arrays and Hashtables.

Sort-Object: put things in order

Sort-Object sorts by one or more properties, ascending by default:

POWERSHELL
Get-Process | Sort-Object -Property WS -Descending
Get-ChildItem | Sort-Object Length, Name

Sorting is case-insensitive by default; add -CaseSensitive to change that. When properties hold numbers, they sort as numbers, but a property that holds numbers as text sorts as text, so "10" comes before "9". If that bites you, cast in a calculated sort key.

To sort one property up and another down, give hashtables:

POWERSHELL
Get-Process | Sort-Object @{ Expression = 'Name'; Descending = $false }, @{ Expression = 'WS'; Descending = $true }

Sort-Object -Unique removes duplicates after sorting. It is also a blocking cmdlet: it must receive every object before it can output the first one, because the smallest item might be the last to arrive. That is why sort comes late in a pipeline, after you have filtered, and why sorting a huge stream uses a lot of memory.

Putting it together

A typical pipeline reads like a recipe: get, filter, sort, select, in that order.

POWERSHELL
Get-Process |
    Where-Object { $_.WS -gt 100MB } |
    Sort-Object WS -Descending |
    Select-Object -First 3 -Property Name, @{ N = 'MB'; E = { [math]::Round($_.WS / 1MB) } }

Read it aloud: take the processes, keep those using more than 100 MB, order them by memory with the biggest first, keep the top three, and show the name and the memory in megabytes. Each step receives objects and passes objects on.

Stand-in: an array pipeline in JavaScript

Here the "pipeline" is plain function calls on an array. where is Where-Object, select is Select-Object (with first, skip, unique and calculated properties given as a { name, expr } object), and sort is Sort-Object (stable, case-insensitive for strings, with a descending flag). The sample processes are made up.

JS Filter, select and sort a list of processes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The result is the three largest processes, with a calculated MB column. Notice that sorting by name puts Slack between pwsh and svchost, because text is compared case-insensitively, just as Sort-Object does by default.

The next stand-in shows two behaviours that surprise newcomers: -Unique keeps the first occurrence of each value, and -ExpandProperty returns bare values instead of objects with one property.

JS Unique values and expanding a property

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real here and what is the stand-in: the behaviour (unique keeps the first, expand gives values, sort then take the first N) matches PowerShell. The code is JavaScript, and unlike PowerShell it processes whole arrays at once instead of streaming one object at a time.

When a pipeline gives odd results, run it one stage at a time and end each trial with Get-Member (see Getting Help). It tells you the exact type and property names the next stage will see.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command returns only the running services?

    Where-Object filters objects with a test, and $_ is the current object. Select-Object picks properties and Sort-Object orders objects, neither of them filters by a comparison.
  2. 2. What is the difference between Select-Object -Property Name and Select-Object -ExpandProperty Name?

    -Property builds new objects containing only the named properties. -ExpandProperty unwraps the value of one property, so the next command receives plain strings or numbers.
  3. 3. Why should Sort-Object usually come after Where-Object, not before?

    Sort-Object is a blocking cmdlet: it needs all input before it can output anything. Filtering first leaves less to hold and sort.
  4. 4. What does @{ N = 'MB'; E = { $_.WS / 1MB } } give you when used in Select-Object?

    A hashtable with a name and an expression (N and E are allowed short forms) defines a calculated property. The expression runs once per input object with $_ as that object.

Summary

  • Where-Object keeps objects whose test is true; $_ or $PSItem is the current object, and a single comparison can use the brace-free form.
  • Filter left: use a cmdlet's own parameters (-Filter, -Name) before Where-Object so fewer objects are created.
  • Select-Object picks properties, takes -First, -Last and -Skip, removes duplicates with -Unique, and -ExpandProperty unwraps values.
  • Calculated properties are hashtables with a name and an expression, and they rename or compute columns.
  • Sort-Object is case-insensitive by default, accepts several keys, uses -Descending and per-key hashtables, and is blocking.
  • A good pipeline reads get, filter, sort, select, and formatting comes last.

Next, count and summarize what you have filtered in Group-Object, Measure-Object and ForEach-Object.