0
0
PowerShellscripting~10 mins

Where-Object for filtering in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Where-Object for filtering
Start with a collection
Apply Where-Object filter
Evaluate condition on each item
If True
Keep item
If False
Discard item
Output filtered collection
The flow starts with a collection, applies a filter condition to each item, keeps items that match, and outputs the filtered collection.
Execution Sample
PowerShell
1..5 | Where-Object { $_ -gt 3 }
# Filters numbers greater than 3 from 1 to 5
This code filters numbers from 1 to 5, keeping only those greater than 3.
Execution Table
StepInput Item ($_)Condition ($_ -gt 3)ResultActionOutput So Far
11FalseDiscardSkip item[]
22FalseDiscardSkip item[]
33FalseDiscardSkip item[]
44TrueKeepAdd to output[4]
55TrueKeepAdd to output[4, 5]
💡 All items processed; output contains only items where condition is True.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
$_N/A12345N/A
Output[][][][][4][4, 5][4, 5]
Key Moments - 2 Insights
Why does the output only include 4 and 5, not 3?
Because the condition $_ -gt 3 means 'greater than 3'. The number 3 is not greater than 3, so it is discarded as shown in steps 3 of the execution_table.
What does $_ represent inside the Where-Object script block?
The $_ variable represents the current item being checked from the input collection, as seen in the execution_table under 'Input Item ($_)' column.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output after processing the 4th item?
A[1, 2, 3, 4]
B[3, 4]
C[4]
D[4, 5]
💡 Hint
Check the 'Output So Far' column at step 4 in the execution_table.
At which step does the condition $_ -gt 3 become true for the first time?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Condition ($_ -gt 3)' column in the execution_table.
If the condition changed to $_ -ge 3, what would be the output after all steps?
A[3, 4, 5]
B[4, 5]
C[1, 2, 3]
D[1, 2, 3, 4, 5]
💡 Hint
Consider that -ge means 'greater than or equal to' and check which items satisfy this.
Concept Snapshot
Where-Object filters items from a collection.
Syntax: collection | Where-Object { condition }
$_ is the current item.
Only items where condition is True are kept.
Useful for selecting specific data easily.
Full Transcript
This visual execution shows how Where-Object filters a list of numbers from 1 to 5 by keeping only those greater than 3. Each number is checked one by one. If the number is greater than 3, it is added to the output. Otherwise, it is skipped. The variable $_ holds the current number being checked. The output after processing all numbers is [4, 5]. This helps beginners see how filtering works step-by-step.