The Two Faces of -match

by Feb 9, 2012

The -match operator can be extremely useful because it accepts regular expression patterns and extracts the information that matches the pattern:

PS> 'PC678 had a problem' -match 'PC(\d{3})'
True
PS> $matches
Name                       Value
----                           -----
1                              678
0                              PC678

PS> $matches[1]
678

However, sometimes -match does not seem to fill $matches:

PS> Remove-Variable matches
PS> 'PC678 had a problem', 'PC112 was ok', 'SERVER12 was ok', 'PC612 not checked' `
>> -match 'PC(\d{3})'
>>
PC678 had a problem PC112 was ok PC612 not checked PS> $matches

As it turns out, -match works differently when applied to a collection (a comma-separated list of multiple items). Here, it filters out those items that match the pattern. That's why in the example above, the entry 'SERVER12 was ok' was filtered out. When applied to collections, -match does not populate $matches. If $matches still does contain information, then it is a left-over from a previous call to -match.

Twitter This Tip! ReTweet this Tip!