PowerTip: Use PowerShell to Check String for a Match

PowerTip: Use PowerShell to Check String for a Match

  • Comments 4
  • Likes

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'

True

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • 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.