PowerShell Array Filter - Filter One PowerShell Array With Another Array Print E-mail
Written by Darwin Sanoy   
Thursday, May 15, 2014 5:55am

In many languages combining or unisecting arrays is part of the standard operators or they have special operators to do this.  PowerShell does not have special operators and it has taken me a very long time to figure out how to make it do this!

Array filtering is one of those rarely used items that also saves buckets of time and many lines of codes when it is actually applicable.

In my case I want the script to accept "a list of things to include" but to successfully configure the target item, I must turn it into a "list of things to exclude".  This can be done by comparing the user specified array to the array of valid values.

Another time when this is very useful is when a variable of input contains an array of values and you need to know if all the values comply with a set of valid values.  If you are working with a script or function parameter, this is most easily done with the "validateset" parameter qualifier - however, if this is in data you read in from a file or other source, this method can help out.

It turns out that Select-String has the smarts to compare every value in an array of values to every value in another array of values, but there are some additional operators required to get our desired result.

Here is the code and the results it produces:

PS C:\> @("List","of","values","to","be","Filtered") | select-string -pattern @("of","Be","List","TO") -simplematch -notmatch

Notice that the default for -notmatch is case insensitivity.

Here is code that identifies we have an invalid value in a data list (using my favorite type accelerator [bool] to save many lines):


PS C:\> $InvalidValuesPresent = [bool](@("List","of","values","to","be","Filtered") | select-string -pattern @("of","Be","List","TO") -simplematch -notmatch)
PS C:\> $InvalidValuesPresent


If you prefer a function, try this:

Function ArrayFilter ($ArrayToBeFiltered,$FilterArray) {

   Return $ArrayToBeFiltered | select-string -pattern $FilterArray -simplematch -notmatch


As always - if you have a more efficient way to do this, please add a comment!