36

As PowerShell has many SQL query-like cmdlets, is there a fast way to check if object is in list of other objects with the Where-Object cmdlet?

Something like in SQL:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

Of course I can write a simple subroutine, but I was just wondering if there is such feature.

0

1 Answer 1

52

You can use the -contains operator:

Get-ColumnNames $table | Where-Object { value1,value2,... -contains $_ }

It's backwards, though with the collection of values on the left side.

In PowerShell 3 you can also use the -in operator:

Where-Object { $_ -in value1,value2,... }

or even

Where-Object -In value1,value2,...

Also, a quirk of how PowerShell works with comparison operators, you can apply them directly to a collection on the left side:

Where-Object { value1,value2,... -eq $_ }

The -eq operator here will either yield the respective element if it is in the list, or $null (which coerces to $false).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.