Powershell: -contains vs. -match and -like
October 2012
I recently discovered a problem where the Where-Object –contains operator wasn’t doing what I thought it was, i.e. the equivalent of String.Contains() in C#. For example:
(Get-Item .\MyDirectory) | where { $_.Attributes -contains “Directory” }
Is not the same as:
(Get-Item .\MyDirectory) | where { $_.Attributes -match “Directory” }
The former fails if the directory has more than one attribute. The reason for this is:
-contains is designed to work on arrays, not strings (referred to as a containment operator)
-match looks for a match inside a string and supports regexes
-like looks for a match inside a string and supports wildcards
So if the directory only has one attribute then –contains sees it as an array with a single entry “Directory” and returns true.
But if the directory has multiple attributes then –contains still sees it as an array with a single entry but the value of that entry is “Directory,NotIndexed” so returns false.
http://www.techotopia.com/index.php/WindowsPowerShell1.0ComparisonandContainmentOperators