Filter Data in PowerShell: Where-Object Patterns
Large result sets are overwhelming. Learn to filter and see only what matters.
How It Works
Where-Object lets you write conditions like 'show only files bigger than 1MB' or 'show only .log files'. The pipe (|) sends results to Where-Object, which filters them.
This transforms overwhelming result sets into focused, useful information.
Code Examples
Find Specific File Type
# Show only .log files
Get-ChildItem | Where-Object {$_.Name -like "*.log"}
# $_.Name is the filename
# -like uses pattern matching
Find Files by Size
# Show files bigger than 1MB
Get-ChildItem -File | Where-Object {$_.Length -gt 1MB}
# Show files smaller than 100KB
Get-ChildItem -File | Where-Object {$_.Length -lt 100KB}
Find Recent Changes
# Files modified in last 7 days
Get-ChildItem | Where-Object {$_.LastWriteTime -gt (Get-Date).AddDays(-7)}
# Files older than 90 days
Get-ChildItem | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-90)}
Combine Multiple Conditions
# Find .log files bigger than 1MB modified in last 30 days
Get-ChildItem | Where-Object {$_.Name -like "*.log" -and $_.Length -gt 1MB -and $_.LastWriteTime -gt (Get-Date).AddDays(-30)}
Most Used Options
- -eq - Equals exactly
- -like - Pattern match (use *)
- -gt - Greater than
- -lt - Less than
- -and - Both conditions true
The Trick: Power Usage
Find what's eating your disk space:
Get-ChildItem -File -Recurse | Where-Object {$_.Length -gt 100MB} | Sort-Object Length -Descending
# Shows files over 100MB, biggest first
# Great for cleanup!
Find files to delete safely:
# Find .tmp files older than 30 days
Get-ChildItem *.tmp | Where-Object {$_.LastWriteTime -lt (Get-Date).AddDays(-30)} | Remove-Item -WhatIf
# -WhatIf shows what would happen without actually deleting!
Learn It Through Practice
Stop reading and start practicing:
The interactive environment lets you type these commands and see real results.
Part of PowerShell for Beginners
This is part of the PowerShell for Beginners series:
- Getting Started - Your first commands
- Command Discovery - Find what exists
- Getting Help - Understand commands
- Working with Files - Copy, move, delete
- Filtering Data - Where-Object and Select-Object
- Pipelines - Chain commands together
Related Resources
Summary
You now understand:
- How this command works
- The most useful options
- One powerful trick
- Where to practice hands-on
Practice these examples until they're automatic. Mastery comes from repetition.
Practice now: Head to the interactive environment and try these commands yourself. That's how PowerShell clicks for you!
What would you like to master next?
This article was originally published by DEV Community and written by arnostorg.
Read original article on DEV Community