PowerShell Where-Object Command Tutorial

PowerShell is an object-oriented scripting language and command line. Every command in PowerShell returns an object which contains properties. Even The return value is a string or integer it is actually a string object or integer object.

Comparison

One of the most popular use cases for the Object-Where command is comparing an object which is generally a command output. The comparison will be done according to output properties and only matched lines will be returned. The comparison generally executed ver objects which contain multi-line content or output. In the following example, we will use comparison operators where we will match the Process ID. The Id is a property of the Get-Process command result and the 8244 is the process ID we want to compare.

Get-Process | Where-Object Id -EQ 8244

Alternative this command can be also called like below. The difference is that the properties are expressed explicitly in the following command. The -Property is used to specify the property name we want to compare in the returning object. The -Value is the value we want to compare. The -EQ means equal.

 Get-Process | Where-Object -Property Id -EQ -Value 8244

Filter Services

The Where-Object command can be used to filter and list services according to different properties and parameters. In this part we will provides filters about services like list only running services, list only stopped services etc.

First we will list only running services by setting the Status as “Running”

Get-Service | Where-Object Status -eq "Running"

With the following PowerShell command stopped processes can be listed.

 Get-Service | Where-Object Status -eq "Stopped"

Filter Processes

Another popular command is the Get-Process command which is used to list processes. the Where-Object is used to filter these processes according to different properties like Process ID, Memory Usage, CPU Usage, Name, Status, etc.

READ  "ipconfig /all" - List All IP Configuration In Windows

In the following example, we will filter the processes according to their name by using the ProcessName property. We will filter the processes which name contains the “ex” by using the -Match property.

Get-Process | Where-Object ProcessName -Match "ex"

We can also filter and list processes that have CPU usage of more than 5 seconds by using the CPU attribute and -gt comparison operator which means “greater than“.

Get-Process | Where-Object CPU -gt 5

Leave a Comment