Where-Object

Unlocking the Power of Where-Object

Welcome back to Wahmans Powershell blog! Today we’re diving into one of the most frequently used and incredibly powerful cmdlets in the PowerShell toolbox: Where-Object.

Where-Object allows you to filter objects in a collection based on the values of their properties. Officially, Microsoft describes it as: Selects objects from a collection based on their property values — and that’s exactly what it does. Whether you’re managing files, users, services or just iterating over objects, Where-Object is your go-to filter tool in PowerShell.

Basic Syntax

collection | Where-Object { condition }

Let’s walk through some real-world examples from beginner to advanced usage so you can see it in action.

Example 1: Filtering Numbers (Beginner)

Let’s start with a plain example — filtering numbers in an array. Suppose you want all numbers greater than 5:

$numbers = 1..10
$filtered = $numbers | Where-Object { $_ -gt 5 }
$filtered

This will output 6 through 10. The $_ represents the current object in the pipeline.

Example 2: Get Running Services (Intermediate)

Now, let’s use Where-Object to filter Windows services that are currently running:

Get-Service | Where-Object { $_.Status -eq 'Running' }

This is particularly useful for quickly identifying what’s active on your system without needing a GUI.

Example 3: Filtering Files by Extension (Intermediate)

Suppose you want to find all .log files in a directory:

Get-ChildItem -Path 'C:\Logs' | Where-Object { $_.Extension -eq '.log' }

This lines up perfectly when you’re parsing logs or managing storage by file types.

Example 4: Advanced Filtering of AD Users (Advanced)

If you’re working with Active Directory, you can filter users who haven’t changed their password in over 90 days:

Import-Module ActiveDirectory
$threshold = (Get-Date).AddDays(-90)
Get-ADUser -Filter * -Properties PasswordLastSet | 
    Where-Object { $_.PasswordLastSet -lt $threshold }

Now that’s some serious automation value — helping administrators stay proactive with user password management.

Wrap Up

Where-Object is one of those cmdlets that you’ll keep coming back to. The more you use PowerShell, the more you’ll appreciate how critical it is for object filtering and script customization.

Happy scripting, and I will see you in the next post!

Leave a Reply

Your email address will not be published. Required fields are marked *