0
0
PowerShellscripting~5 mins

Where-Object for filtering in PowerShell

Choose your learning style9 modes available
Introduction
Use Where-Object to pick only the items you want from a list or collection. It helps you filter data easily.
You have a list of files and want only those bigger than 1MB.
You want to find processes using more than 50% CPU.
You need to select users from a list who are active.
You want to filter events from a log by date.
You want to get services that are currently running.
Syntax
PowerShell
collection | Where-Object { condition }
The condition inside the braces { } decides which items to keep.
Use $_ to represent the current item in the collection.
Examples
Selects processes using more than 100 seconds of CPU time.
PowerShell
Get-Process | Where-Object { $_.CPU -gt 100 }
Filters files to only those with the .txt extension.
PowerShell
Get-ChildItem | Where-Object { $_.Extension -eq ".txt" }
Filters numbers to only even numbers.
PowerShell
$numbers = 1..10
$numbers | Where-Object { $_ % 2 -eq 0 }
Sample Program
This script gets all files in the current folder, filters those larger than 1,000,000 bytes (1MB), and prints their names.
PowerShell
$files = Get-ChildItem -Path .
$largeFiles = $files | Where-Object { $_.Length -gt 1000000 }
foreach ($file in $largeFiles) {
    Write-Output $file.Name
}
OutputSuccess
Important Notes
Where-Object works with any collection, not just files or processes.
You can combine multiple conditions using -and or -or inside the braces.
Remember $_ always means the current item being checked.
Summary
Where-Object helps you filter collections by conditions.
Use $_ to refer to each item inside the filter block.
It makes scripts cleaner by selecting only what you need.