Learn about Windows PowerShell
Summary: Learn how to check a string to see if it contains another string.
How can I use Windows PowerShell to check a string to see if it contains another string?
Use the –Match operator:
PS C:\> $a = [string]"This string contains a number of letters"
PS C:\> $a -match 'a number'
Technically, the -match operator expects a regular expression on the right. This might cause you problems if the string you're searching for contains special characters like square brackets, parentheses, and several others. To avoid that problem when you're trying to find a literal string, use [regex]::Escape():
PS C:\> $string = [string]"This string contains [a few] (tricky)+characters."
PS C:\> $substring = 'contains [a few] (tricky)+'
PS C:\> $string -match $substring # False
PS C:\> $string -match [regex]::Escape($substring) # True
@Dave Wyatt You are correct (of course). 'a number' is a very simple regular expression :-) I like your suggestion. It is a whole lot easier to read than the following:
$string -match "\[a few\] \(tricky\)\+characters"
How to check if the string contain a special character?
How come my match operator returns a string and doesn't create $Matches. It worked correctly yesterday but today it returns the pattern I want to match rather than $true or $false and $matches.