Match

The ‘match’ can be anywhere within the string.  Moreover, the pattern does not have to be a complete, and this is the biggest benefit of match.  -Match can use regular expressions for pattern matching.  Incidentally -Match, and the other PowerShell conditional operators, all have a negative form, for example -NotMatch.

Example 1a – Match does not have to be at the beginning

$Person =”Guy Thomas 1949″
$Person -Match “Th”

# Result PS> True

Example 1b – Naturally a completely wrong name is no good

$Person =”Guy Thomas 1949″
$Person -Match “Guido”

# Result PS> False

Example 1c – Wrong date

$Person =”Guy Thomas 1949″
$Person -Match “1939”

# Result PS> False

Note 1: While Guy Thomas 1949 has ’19’, it does not have ‘1939’, thus returns False.

Example 1d – Wildcard?  Rides to the rescue

$Person =”Guy Thomas 1949″
$Person -Match “19?9”

# Result PS> True

Like

 

With PowerShell’s -Like, both sides of the expression have to be the same, fortunately, you can employ the usual wildcards * and ?

Example 2 – Having only part of the string is no good for -Like

$Person =”Guy Thomas 1949″
$Person -Like “Th”

# Result PS> False

Note 4:  Substitute -Match for -Like and the result would be ‘True’.

Example 2a – Just the start of the string not enough

 

$Person =”Guy Thomas 1949″
$Person -Like “Guy”

# Result PS> False

Example 2b – Wildcard * is useful for -Like

$Person =”Guy Thomas 1949″
$Person -Like “Guy*”

# Result PS> True

Contains

The conditional operator -Contains is similar to -eq, except it returns ‘True’ or ‘False’.  -Contains is designed for situations where you wish to test for one particular item in a collection, array or a hashtable.

Example 3a  -Contains checks each item between the commas

# PowerShell -Contains
$Name = “Guy Thomas”, “Alicia Moss”, “Jennifer Jones”
$Name -Contains “Alicia Moss”

# Result PS> True

Example 3b  -Contains requires exact equality

# PowerShell -Contains
Clear-Host
$Name = “Guy Thomas”, “Alicia Moss”, “Jennifer Jones”
$Name -Contains “Jones”

# Result PS> False