I was writing a script the other day where I want to return a collection of Services based on the name. It took me a few minutes to figure out how to do this, so I thought I’d jot it down. Nothing revolutionary, but I’ve definitely found this pattern to be handy.
Let’s start with a comma separated list of objects we want to filter by. In this case I only want to return objects that start with “a”, “c”, “e”, or “g”. I’ll take that list, and split it into an array.
# List we want to filter against
# Split it into an array
$filterList = ‘a,c,e,g’.Split(",")
Next, I’ll generate a collection of objects to try and filter. I’ll just use a function to make life easy:
# Function to generate a collection of objects to test on function Create-TestCollection { # Turn this into an object to filter $objectList = 'a,b,c,d,e,f,g'.Split(",") foreach($object in $objectList) { $output = new-object PSObject $output | add-member noteproperty Name $object Write-Output $output } } # Populate the variable to test with our collection of objects $collection = Create-TestCollection
Now $collection contains a list of objects with a single Name property containing “a”, “b”, “c”, “d”, etc.
Now list filter $collection using a Where:
Write-Host "Objects from the Collection where the Name property exists in an Array" # Filter the collection of objects based on a CSV list $collection | Where {$_.Name -and $filterList -eq $_.Name }
And it will return only the objects from our initial comma separated list:
Name
----
a
c
e
g
This also works with other strings:
# An array we want to filter $collection2 = 'a,d,g,j,m'.Split(",") Write-Host "Strings in an Array where that exist in an Array" # Filter the collection of objects based on a CSV list $collection2 | Where {$_ -and $filterList -eq $_ }
Strings in an Array where that exist in an Array
a
g
Enjoy…
David