How to Use Where-Object in PowerShell: Filter Objects Easily
Use
Where-Object in PowerShell to filter objects from a collection by specifying a condition script block. It processes each object and returns only those that meet the condition, like Get-Process | Where-Object { $_.CPU -gt 100 } to find processes using more than 100 CPU seconds.Syntax
The basic syntax of Where-Object is:
Collection | Where-Object { condition }$_represents the current object in the pipeline.- The
conditionis a script block that returns$trueor$false.
Only objects where the condition is true are passed through.
powershell
Collection | Where-Object { <condition> }Example
This example lists all running processes that use more than 100 CPU seconds. It shows how Where-Object filters objects based on a property.
powershell
Get-Process | Where-Object { $_.CPU -gt 100 } | Select-Object -Property Id, ProcessName, CPUOutput
Id ProcessName CPU
-- ----------- ---
1234 chrome 150.5
5678 powershell 120.3
Common Pitfalls
Common mistakes when using Where-Object include:
- Forgetting to use
$_to refer to the current object. - Using assignment
=instead of comparison-eqor other operators. - Not using curly braces
{ }around the condition.
Example of wrong and right usage:
powershell
# Wrong: missing $_ and using = instead of -eq
Get-Process | Where-Object { CPU = 100 }
# Right: correct comparison and use of $_
Get-Process | Where-Object { $_.CPU -eq 100 }Quick Reference
| Operator | Description | Example |
|---|---|---|
| -eq | Equals | { $_.Name -eq 'notepad' } |
| -ne | Not equals | { $_.Id -ne 1234 } |
| -gt | Greater than | { $_.CPU -gt 50 } |
| -lt | Less than | { $_.Handles -lt 100 } |
| -like | Wildcard match | { $_.ProcessName -like '*chrome*' } |
Key Takeaways
Use Where-Object to filter collections by conditions in PowerShell pipelines.
Always use $_ to refer to the current object inside the condition script block.
Use comparison operators like -eq, -gt, -lt inside the script block for filtering.
Enclose the condition in curly braces { } to define the script block.
Avoid using assignment (=) instead of comparison operators in conditions.