Ways to use Where-Object in PowerShell

PowerShellMicrosoft TechnologiesSoftware & Coding

Where−Object or (alias: Where) in PowerShell is used to filter the data output provided through the Pipeline.

There are two methods we can use the Where−Object for the pipeline inputs.

  • a. ScriptMethod −

In this method, we use ScriptBlock to filter the output with the Property name, value, and the comparison operator.

Get−Service | Where−Object{($_.StartType −eq 'Automatic') −and ($_.Status −eq 'Stopped')}

You can also use Alias: Where instead of Where−Object.

Get−Service | Where{($_.StartType −eq 'Automatic') −and ($_.Status −eq 'Stopped')}

Other Syntax ‘?’ (Question Mark) can also be used Instead of the Where−Object command.

Get−Service | ?{($_.StartType −eq 'Automatic') −and ($_.Status −eq 'Stopped')}

The above commands will get the Services with the StartType AUTOMATIC and the status STOPPED.

  • b. Comparison Statement −

This method is more like a natural language and it was introduced in PowerShell 3.0 version and before that, there was only a scriptblock method. To use this method we will use Property Name, Value, and the comparison statement but without script block and using Property and Value parameter.

For example, to filter the output of the services which have StartType Disabled, we will use the below code.

Get−Service | Where−Object −Property StartType −EQ −Value Disabled

When you provide a single property for example Array to Where−Object command, the value of the property is treated as a Boolean expression, and when the value length is not zero the output is true.

For example,

PS C:\> ("Windows","","PowerShell","","Azure") | Where−Object Length
Windows
PowerShell
Azure

Similar commands are,

("Windows","","PowerShell","","Azure") | where{$_.length −gt 0}

Or,

("Windows","","PowerShell","","Azure") | Where−Object Length −GT 0
raja
Published on 25-Jan-2021 07:11:07
Advertisements