0
0
PowershellHow-ToBeginner · 3 min read

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 condition is a script block that returns $true or $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, CPU
Output
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 -eq or 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

OperatorDescriptionExample
-eqEquals{ $_.Name -eq 'notepad' }
-neNot equals{ $_.Id -ne 1234 }
-gtGreater than{ $_.CPU -gt 50 }
-ltLess than{ $_.Handles -lt 100 }
-likeWildcard 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.