I will explain a very useful cmdlet in PowerShell: PowerShell Where-Object in this tutorial. This command lets users filter and select specific items from a set of data. Let us understand with some examples.
The Where-Object cmdlet picks out objects with certain property values from a group of objects. It’s like a sieve that catches only the items you want. You can use it to find files made after a certain date, events with a specific ID, or computers running a particular version of Windows.
Using Where-Object can make your PowerShell scripts more efficient. Instead of sorting through all the data yourself, you can tell PowerShell exactly what you’re looking for. This saves time and makes your code cleaner and easier to read. Let me explain how to use the PowerShell Where-Object cmdlet with some examples.
PowerShell Where-Object Cmdlet
The Where-Object cmdlet in PowerShell is used to filter data. It allows users to select specific objects from a collection based on certain criteria.
This cmdlet works within the PowerShell pipeline, processing objects as they flow through. It examines each object and only passes those that meet the specified conditions.
Where-Object uses a script block to define the filtering criteria. This block contains the logic that determines which objects to keep or discard.
Here’s a basic example:
Get-Process | Where-Object {$_.CPU -gt 10}
This command lists all processes using more than 10% CPU.
I executed the above PowerShell script, and you can see the output in the screenshot below:
The FilterScript parameter is key to Where-Object’s functionality. It accepts complex expressions, enabling detailed filtering of data.
Where-Object can be used with many other PowerShell cmdlets. It’s especially useful when working with large datasets, as it can significantly reduce the amount of information passed down the pipeline.
By filtering early in a command chain, Where-Object helps improve script performance. It cuts down on unnecessary processing of unwanted data.
PowerShell offers two syntax options for Where-Object: the older “script block” style and the newer “comparison” style introduced in PowerShell 3.0. Both achieve the same results but with slightly different syntax.
Check out PowerShell Get-Date Cmdlet
PowerShell Where-Object Syntax
The Where-Object cmdlet filters objects based on specific conditions. It uses parameters, pipelines, and script blocks to select items that match given criteria.
Identifying Parameters
Where-Object has two main parameters: FilterScript and InputObject. FilterScript defines the conditions for filtering. InputObject takes input from the pipeline or as a direct argument.
The cmdlet’s short name is ‘where’. This makes scripts shorter and easier to read.
Basic syntax:
Get-Service | Where-Object {$_.Status -eq 'Running'}
This command lists only running services.
Working with the Pipeline
Where-Object often works with other cmdlets through the pipeline. It filters objects passed from previous commands.
Example:
Get-ChildItem | Where-Object {$_.Length -gt 1MB}
This finds files larger than 1 megabyte in the current folder.
The $_ symbol is an automatic variable. It stands for the current object in the pipeline.
Using Script Blocks for Custom Filters
Script blocks let you create complex filters. They use comparison and logical operators to check multiple conditions.
Example with multiple conditions:
Get-Process | Where-Object {$_.CPU -gt 10 -and $_.WorkingSet -gt 50MB}
This finds processes using over 10% CPU and 50 MB of memory.
You can use -lt (less than), -gt (greater than), -eq (equal to), and other operators in script blocks.
Check out Rename Multiple Files Using PowerShell
Comparisons and Conditions
PowerShell’s Where-Object cmdlet uses various comparison operators and conditions to filter objects. These parameters let users select specific items from data streams based on custom criteria.
Standard Comparison Operators
Where-Object supports common comparison operators like -eq (equal), -ne (not equal), -gt (greater than), and -lt (less than). These work with numbers and strings.
Get-Process | Where-Object { $_.CPU -gt 10 }
This command finds processes using over 10% CPU. The -le (less than or equal) and -ge (greater than or equal) operators are also useful.
For exact matches, -eq is best. But -like allows wildcard patterns:
Get-ChildItem | Where-Object { $_.Name -like "*.txt" }
This finds all text files in a folder.
Using Case Sensitivity
PowerShell comparisons are case-insensitive by default. To make them case-sensitive, add ‘c’ before the operator:
Get-Process | Where-Object { $_.Name -ceq "NOTEPAD" }
This only matches “NOTEPAD” exactly, not “notepad” or “Notepad”. Other case-sensitive operators include -cne, -cgt, -clt, -cge, and -cle.
Containment and Regular Expressions
The -contains operator checks if a value is in a list:
"Apple","Banana","Cherry" -contains "Banana"
This returns true. For more complex text matching, use -match with regular expressions:
Get-ChildItem | Where-Object { $_.Name -match "^[aeiou].*.txt$" }
This finds text files starting with a vowel. The -notmatch operator does the opposite, excluding matches.
Regular expressions offer powerful text filtering options. They can find patterns like email addresses or phone numbers in data.
Read PowerShell Global Variables
Apply Filters on Objects using Where-Object
Where-Object lets you filter PowerShell objects based on their properties. This cmdlet works with files, processes, services, and more. It uses comparison statements to match specific values.
Filter Files and Directories
Get-ChildItem and Where-Object team up to find files that meet certain criteria. You can filter by name, size, or date modified.
Here’s how to find text files changed in the last week:
Get-ChildItem -Path C:\Documents -Filter *.txt | Where-Object { $_.LastWriteTime -gt (Get-Date).AddDays(-7) }
This command checks the LastWriteTime property of each file. It only keeps files modified within 7 days.
You can also filter by file size:
Get-ChildItem -Path C:\Pictures | Where-Object { $_.Length -gt 1MB }
This finds pictures larger than 1 megabyte.
Manage Processes and Services
Where-Object helps sort through running processes and services. You can filter by name, status, or other properties.
To find all stopped services:
Get-Service | Where-Object { $_.Status -eq 'Stopped' }
This checks the Status property of each service.
For processes, you might want to find those using lots of memory:
Get-Process | Where-Object { $_.WorkingSet -gt 100MB } | Sort-Object WorkingSet -Descending
This command finds processes using over 100MB of RAM and sorts them.
You can also filter services by their startup type:
Get-Service | Where-Object { $_.StartType -eq 'Automatic' }
This lists only services set to start automatically.
Read How to Add Quotes in PowerShell?
Integrate Where-Object with Other Cmdlets
Where-Object works well with many PowerShell cmdlets to filter and refine data. It fits into pipelines to process command output and select specific objects or properties.
Combine with Get-Command
Get-Command lists available cmdlets and functions. Where-Object helps narrow down those results.
To find cmdlets with “process” in the name:
Get-Command | Where-Object Name -like "*process*"
This returns only matching commands. The -like operator allows wildcards for flexible matching.
For commands in a specific module:
Get-Command | Where-Object ModuleName -eq "Microsoft.PowerShell.Management"
This filters commands to just those in the specified module.
Use with Select-Object for Refined Output
Where-Object and Select-Object work together to filter and format data. Where-Object picks which objects to keep. Select-Object chooses which properties to display.
To get running processes using over 100 MB of memory:
Get-Process | Where-Object WorkingSet -gt 100MB | Select-Object Name, WorkingSet
This shows only the process name and memory use. The pipeline filters processes first, then selects specific properties.
To find the five largest files in a folder:
Get-ChildItem | Where-Object Length -gt 1MB | Select-Object Name, Length | Sort-Object Length -Descending | Select-Object -First 5
This combines multiple cmdlets to filter, sort, and limit results.
Read Create a Log File using PowerShell
PowerShell Where-Object Examples
Now, let me show you some examples of using the PowerShell Where-Object.
Here is the PowerShell cmdlet to find stopped services using the Where-Object.
Get-Service | Where-Object {$_.Status -eq "Stopped"}
This command lists all stopped services on your system.
To find large files over 100 MB, you can use the Where-Object PowerShell cmdlet like below:
Get-ChildItem C:\ -Recurse | Where-Object {$_.Length -gt 100MB}
It searches the C: drive for files bigger than 100 megabytes.
You can filter processes by name:
Get-Process | Where-Object {$_.ProcessName -like "*chrome*"}
This shows all running processes with “chrome” in the name.
To find files changed in the last 24 hours:
$date = (Get-Date).AddDays(-1)
Get-ChildItem | Where-Object {$_.LastWriteTime -gt $date}
It lists files modified within the past day.
Using regular expressions lets you search for specific patterns:
Get-ChildItem | Where-Object {$_.Name -match "^[A-Z].*\.txt$"}
This finds text files that start with a capital letter.
These examples show how Where-Object helps filter data in PowerShell. It works with many cmdlets to narrow down results based on different criteria.
Read How to Compare Dates in PowerShell?
Common Parameters and Modifiers for Where-Object
Where-Object supports several common parameters and modifiers to refine filtering operations. These options give users more control over how objects are selected from the pipeline.
The -FilterScript parameter lets you specify a script block with filtering criteria. It uses comparison operators like -eq, -ne, -gt, -lt to evaluate object properties.
Containment operators are useful for checking if values exist within collections:
- -Contains: Tests if a value is in an array
- -In: Checks if an object is in a specified collection
- -NotIn: Excludes objects found in a given set
Pattern matching modifiers allow flexible text comparisons:
- -Like: Matches strings using wildcard characters
- -NotLike: Excludes strings matching a pattern
- -Match: Finds text using regular expressions
- -NotMatch: Excludes text matching a regex
The CommonParameters supported by Where-Object include:
- -ErrorAction: Controls error handling
- -ErrorVariable: Stores error messages
- -OutVariable: Saves output to a variable
- -PipelineVariable: Passes data between commands
These parameters and modifiers make Where-Object more helpful for filtering PowerShell objects.
Frequently Asked Questions
Where-Object is a powerful PowerShell cmdlet for filtering objects. It can filter based on property values, use multiple conditions, and work with strings and wildcards. Here are some common questions about using the Where-Object effectively.
How can I use Where-Object to filter objects based on a specific property value?
To filter objects by a property value, use this syntax:Get-Process | Where-Object {$_.CPU -gt 10}
This command finds processes using more than 10% CPU.
What is the syntax for using Where-Object with multiple conditions?
For multiple conditions, use logical operators like -and or -or:Get-Service | Where-Object {$_.Status -eq 'Running' -and $_.StartType -eq 'Automatic'}
This finds services that are running and set to start automatically.
How do I use Where-Object to check if a property’s value contains a particular string?
Use the -like operator with wildcards:Get-ChildItem | Where-Object {$_.Name -like '*log*'}
This command finds files with “log” in their name.
Can Where-Object be used to compare a list of values and how is it implemented?
Yes, use the -in operator with an array:Get-Service | Where-Object {$_.Name -in ('WinRM', 'Spooler', 'W32Time')}
This finds services with names matching the given list.
Is there a way to use Where-Object with wildcard patterns, such as the like operator?
The -like operator supports wildcards:Get-ChildItem | Where-Object {$_.Name -like 'test*.txt'}
This finds files starting with “test” and ending with “.txt”.
How to filter objects that have properties starting with a certain string using Where-Object?
Use the -match operator with a regular expression:Get-Process | Where-Object {$_.Name -match '^svc'}
This finds processes with names starting with “svc”.
Conclusion
In this tutorial, I explained how to use the PowerShell Where-Object cmdlet with some useful examples. You can use this cmdlet to filter data; it helps users select specific items from large sets of information.
I suggest you try these examples and let me know if you face any issues.
You may also like:
I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com