🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Where-Object

Where-Object is a cmdlet that keeps only the pipeline items that pass a test. It filters a stream down to the items you actually want.

Keep numbers greater than five

Pipe a range into Where-Object. The test keeps only numbers greater than five.

(1..10 | Where-Object { $_ -gt 5 }) -join ", "

Keep only even numbers

A number is even when dividing it by two leaves no remainder. The test checks that remainder.

(1..10 | Where-Object { $_ % 2 -eq 0 }) -join ", "

Filter words by their start

Split a sentence into words first. Then keep only the words that start with a chosen letter.

$words = "apple banana cherry grape" -split " "
($words | Where-Object { $_ -like "c*" }) -join ", "

Example

$bigEven = 1..20 | Where-Object { ($_ % 2 -eq 0) -and ($_ -gt 10) }
$bigEven -join ", "

Key points

  • Filter: Where-Object keeps an item only when its test is true.
  • Pipeline item: Inside the test, $_ stands for the item being checked.
  • Test block: The test goes in curly braces after Where-Object.
  • Comparison: A test usually compares $_ with -eq, -gt, or -lt.
  • No match: When nothing passes the test, Where-Object outputs nothing.

In this example, the range 1 to 20 flows into Where-Object. The test keeps a number only when it is even and greater than ten. The surviving numbers are then joined into one line.

Note

Where-Object never changes the items it keeps. It only chooses which ones pass through.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command keeps only the numbers less than 4 from 1 to 10?