What is Where-Object in PowerShell?

Overview

The Where-Object cmdlet is used to filter the resulting data through a pipeline.

Syntax

We'll call Where-Object after the | pipe operator. We can access the current object in the script block using $_:

Where-Object { condition }

Parameter

This command does not take any parameters. It only accepts conditions to filter the output data from the pipeline.

Return value

This method returns the filtered data.

Code example

In the following example, we'll filter the students who have more than five character lengths in their names.

#!/usr/bin/pwsh -Command
#given array of students
$students = @('Daniel', 'Westin', 'Tadeo', 'Hezekiah')
#filter students using Where-Object
$students | Where-Object { $_.Length -gt 5}

Code explanation

In the above code snippet:

  • Line 4: We declare and initialize an array named students.
  • Line 7: We filter out the students whose name length is greater than five characters using Where-Object. We access the current object using $_ and get the length using the in-built Length property, and we compare it using the comparison operator called -gt.

Free Resources