#PSTip Filtering a collection using comparison operators

Note: This tip requires PowerShell 2.0 or above.

Starting with PowerShell 3.0, it is possible to filter a collection for matching or non-matching values using comparison operators. For example, assume that I have a collection with four elements in it.

$Collection = 'test1','test2','test3','test4'

I want to filter this collection and retrieve all values except ‘test3’. How do we do that? We can use comparison operators here. When using a comparison operator, when the left-hand side value is a collection, the comparison results in matching values.

$Collection -ne 'test3'

This returns all elements except ‘test3’.

[Update: 5/29/2014] There are gotchas in using this method for collection filtering. Roman Kuzmin provided a great answer to a question on Stack Overflow that explains these gotchas.

Here is a more practical and real-world example. I was looking for a way to filter a list of URLs for non-empty strings.

$doc = Invoke-WebRequest -Uri 'https://www.python.org/downloads'
foreach ($href in ($doc.links.href -ne '')) {
    $href
}

Remember, the right-hand side value has to be a scalar value.

Share on: