Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object is in a list of objects

Tags:

powershell

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.

like image 743
npocmaka Avatar asked Mar 31 '11 08:03

npocmaka


People also ask

How do you check if an object is in a list of objects Python?

To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.

How do you check if an object is not in a list Python?

“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.

How do you check if a value is in an object Python?

In Python, the built-in functions type() and isinstance() help you determine the type of an object. type(object) – Returns a string representation of the object's type. isinstance(object, class) – Returns a Boolean True if the object is an instance of the class, and False otherwise.

Can we have list of objects?

Yes, it is absolutely fine to have an object contains list of object.


1 Answers

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).

like image 65
Joey Avatar answered Oct 04 '22 05:10

Joey