PowerShell Matching Text
Matching text is a way to test whether a string fits a pattern instead of matching it exactly. You use matching when you only know part of a word, such as its first letters, or when you want to check a whole group of values at once.
Match with wildcards using -like
The * wildcard stands for any characters, including none. -like ignores letter case.
"hello" -like "h*o"
"hello" -like "H*"
"hello" -like "z*"Match a pattern using -match
-match uses a regular expression, a pattern language for text. The ^ symbol means the pattern must start at the beginning of the string.
'hello' -match '^he'
'Hello' -match '^he'
'hello' -match '^lo'Check a group with -contains
-contains checks a whole group of values, and it ignores letter case. The .Contains() method checks inside one string instead, and it cares about case.
1..5 -contains 3
1..5 -contains 9
"red", "green", "blue" -contains "GREEN"
"Hello".Contains("ell")
"Hello".Contains("ELL")Example
$word = "PowerShell"
$word -like "Power*"
$word -match "^Power"
$word.Contains("Shell")
$word.Contains("shell")Key points
- Pattern: a short description of the shape of the text you want, using wildcards or a regular expression.
- -like tests a string against a wildcard pattern, where * stands for any characters.
- -match tests a string against a regular expression pattern, where ^ marks the start of the string.
- -contains tests whether a group of values holds one particular value.
- A string method is a built-in action you call on a string with a dot, such as .ToUpper().
In this example, one word is tested four ways. The wildcard test and the pattern test both pass because the word starts with Power. The .Contains() test passes for Shell with a capital S and fails for shell with a small s, because that method cares about case.
Note
-like, -match, and -contains all ignore letter case, but the .Contains() string method cares about case.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which of these tests returns True?