Share this post:This blog post is part of an ongoing series by Adam Gordon. Adam will walk through each PowerShell command every week, explaining when and how to use them. Adam’s week is dedicated to Where-Object.
When to Use Where-Object
The Where-Object cmdlet allows you to select objects with particular property values from the objects that have been passed to it.
There are two ways to create a Where-Object command starting in Windows PowerShell 3.0
Script block. A script block can be used to specify the property name, comparison operator, or property value. Where-Object returns all objects that the script block statement is true.
Comparison statement. A comparison statement can also be written, which is more natural language than natural language.
How to use “Where-Object”
Get stopped services
(1st) Get-Service | Where-Object $_.Status -eq “Stopped”
where Status -eq “Stopped”
These commands will display a list of services currently being stopped.
Each object that is passed to Where-Object cmdlet is represented by the $_ variable.
The first command uses the script block format. The second uses the comparison statement format.
Processes based on the working set:
Get-Process | Where-Object $_.WorkingSet -GT 25000*1024Get-Process | Where-Object WorkingSet -GT (25000*1024)
These commands list all processes with a working set greater that 25,000 kilobytes.
The WorkingSet property’s value is stored in bytes so the value of 25,000 can be multiplied by 1,024.
Both the statement syntax and script block are interchangeable.
Use the comparison statement format
Where-Object -Property Handles -GE -Value 1000
where Handles -GE 1000
This example shows you how to use the new comparison statements format of the Where Object cmdlet.
The comparison statement format is used by the (1st) command. This command does not use aliases and all parameters contain the parameter name.
The natural use of comparison command format is the (2nd) command. The Where-Object cmdlet names are replaced by the where alias and all optional parameter names are omitted.
Multiple conditions are possible
where ($_.Name -notlike “Microsoft*” -and $_.Name -notlike “PS*”) -and $_.HelpInfoUri
This command uses the Get-Module cmdlet’s -ListAvailable parameter to retrieve all modules on the computer.
) sends the modules to the Where-Object cmdlet, which gets modules whose names do not begin with Microsoft or PS, and have a value for the HelpInfoURI property, which tells PowerShell where to find updated help files for the module.
The And logical operator connects the comparison statements.
This example uses the script block command format.
NOTE: Logical operators such as And or Or are only valid in script blocks. They cannot be used in the Where-Object command’s comparison statement format.
Learn the command from last week: Get-WinEvent.
Do you need PowerShell training? ITProTV offers PowerShell online IT training courses.