PowerTip: Use PowerShell to Check String for a Match

Summary: Learn how to check a string to see if it contains another string.

Hey, Scripting Guy! Question How can I use Windows PowerShell to check a string to see if it contains another string?

Hey, Scripting Guy! Answer Use the –Match operator:

PS C:\> $a = [string]”This string contains a number of letters”

PS C:\> $a -match ‘a number’


Comments (4)

  1. Dave Wyatt says:

    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

  2. Ed Wilson says:

    @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"

  3. pkj says:

    How to check if the string contain a special character?

  4. Jmz215 says:

    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.