Dr.Sys
Dr.Sys

Reputation: 15

Using an Or Statement Within a "Where" in Powershell

I'm making a script that finds all programs with names similar to "Microsoft Office S*" -or "Microsoft Office P*"

I got the code working while searching for one or the other, but not both at the same time. Some examples below:

WORKS

get-wmiobject Win32_Product | Where Name -like "Microsoft Office S*"| Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

WORKS

get-wmiobject Win32_Product | Where Name -like "Microsoft Office S*"| Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

DOESN'T WORK

get-wmiobject Win32_Product | Where Name -like ("Microsoft Office S*" -or "Microsoft Office P*")| Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

DOESN'T WORK

get-wmiobject Win32_Product | Where Name -like ("Microsoft Office S*") -or Name -like ("Microsoft Office S*")| Format-Table IdentifyingNumber, Name, LocalPackage -AutoSize

Upvotes: 1

Views: 7830

Answers (3)

miljbee
miljbee

Reputation: 350

Have a lok at the integrated help :

Get-Help Where

In the available Syntax, you'll find

 Where-Object [-Property] <string> [[-Value] <Object>] -Like [-InputObject <psobject>]  [<CommonParameters>]

In you third sample : "Microsoft Office S*" -or "Microsoft Office P*" evaluates to true, it doesn't work because it's the same as :

Where Name -like $True

Which is always false (except if name value is $True)

For your fourth sample, the get-help shows that the where-object has no 'or' parameter. So it can not work.

When reading the help, keep in mind that the inputObject parameter contains the pipelined psObject.

The proposals solutions are good but I will propose this other form that matches the help :

Where-Object -Property Name -Value '^Microsoft Office S|^Microsoft Office P' -match

If you need a compact One-Liner it's equivalent to :

? Name -match '^Microsoft Office (S|P)'

(? is an alias of where-object)

Upvotes: -1

js2010
js2010

Reputation: 27428

Aside from using a script block and -or with where, a regex like this is convenient:

where name -match 'Microsoft Office S|Microsoft Office P'

Upvotes: -1

AdminOfThings
AdminOfThings

Reputation: 25001

I believe the issue here is not using the Where-Object script block. If you reform your query to the following, your issues should go away.

Get-WmiObject Win32_Product | Where-Object {$_.Name -like "Microsoft Office S*" -or $_.Name -like "Microsoft Office P*"}

Upvotes: 6

Related Questions