Powershell filter: Using where-object and select-object (2021)
2 Min Read
Last Update: February 6, 2023
The Where-Object and Select-Object commands are used to filter and select PowerShell objects in the following topic in the PowerShell Fundamental series. You can precisely define which items are displayed or acted on by using these commands.
Overview: Where-object and Select-object
It’s critical to comprehend the ideas discussed in previous sections before learning how to utilize the Where-Object and Select-Object commands. First and foremost, PowerShell is an object-oriented programming language. Almost every command returns an object with several characteristics that may be independently examined and filtered.
 The Get-Process command, for example, will return various bits of information about currently running Windows processes, such as the start time, and current memory use. Each of these is saved as a Process object’s property. With the Pipeline character: |, PowerShell commands can also be chained together. When you do this, the results of the commands on the left of the pipe are sent to the commands on the right. The processes identified by the Get-Process command will be halted if you pipe Get-Process to Stop-Process, as in Get-Process | Stop-Process. This would try to stop all of the running processes on the system if there was no filtering in place.
Where-object: Syntax, Working, and Examples
The Where-Object command can be used to filter objects based on any property they have.
The “PropertyName” property is the name of the object whose property you’re filtering. ComparisonType is a brief keyword that describes the type of comparison you’re performing. “eq” stands for equals, “gt” stands for greater than, “lt” stands for less than, and “like” stands for a wildcard search. Finally, the FilterValue is the value against which the object’s property is being compared. The Get-Process command, example is shown below with output.
The Select-Object command is another one to become acquainted with. This command is used to restrict or modify the output of other commands. There are numerous applications for it, but one of the most common is to select the first N results of another command.
You can easily control which items you are working on in PowerShell by using the Where-Object and Select-Object commands. You can use these commands to filter the data you’re viewing or to limit actions (like stopping services or removing files) to those that match the filters you set. This series will conclude with the next article. We’ll look at looping through groups of objects in order to perform more complex tasks on a collection of items.
Comments