Majid Hojati
Majid Hojati

Reputation: 1790

PowerShell How to use -and in Where-Object

I want to filter a command result using two conditions. Here are my commands

 $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property ConfigurationFlags -NotLike '*DISABLED*' | ft Name, InstanceId -AutoSize

and the next filter is

 $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize

both of them works separately but I want to join them using and command. I tried to use -AND as following command but it keeps raising errors


 Get-PnpDevice | Sort-Object -Property Name | Where-Object{
      ( ConfigurationFlags -NotLike '*DISABLED*') -and 
      ( FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize

Upvotes: 1

Views: 5912

Answers (2)

Binary Galaxy
Binary Galaxy

Reputation: 59

You can pipe 'Where' clauses together... it's simpler syntax and easier to read

Get-PnpDevice | Sort-Object -Property Name | Where ConfigurationFlags -NotLike '*DISABLED*' | Where FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize

Upvotes: 2

HAL9256
HAL9256

Reputation: 13523

Simply use the The $_ automatic variable in your Where-Object to reference the property names:

Get-PnpDevice | Sort-Object -Property Name | Where-Object{
      ( $_.ConfigurationFlags -NotLike '*DISABLED*') -and 
      ( $_.FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize

Upvotes: 2

Related Questions