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.
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.
“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.
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.
Yes, it is absolutely fine to have an object contains list of object.
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
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With