PowerTip: Finding Letters in Strings with PowerShell

Summary: Learn four ways to use Windows PowerShell to find letters in strings.

Hey, Scripting Guy! Question I want to find out if a string contains the letter “m.” The string is stored in the variable $a as shown here:

$a=”northern hairy-nosed wombat”

Hey, Scripting Guy! Answer Here are a variety of ways to accomplish this:

a.  [string]$a.contains(“m”)

b.  $a.contains(“m”)

c.  [regex]::match($a,"m")

d.  ([regex]::match($a,"m")).success

Comments (8)

  1. K_Schulte says:

    Hi Ed,

    I usually don't add alternatives to your PowerTips, but this time I'm missing the most obvious expression:

    $a -match 'm' or maybe

    $a -like '*m*'

    And, if I think back of VBScript, there is an "indexof" string member, that we can use:

    $a.IndexOf('m') -ge 0


  2. jrv says:

    And today has been brought to you by the letter "M".

  3. jrv says:

    @Ed. Then you should be able to use the rest of the alphabet.  

    I thought 'Sesame Script' was more like "Open sesame'" – You know. LIke Ali Baba.

  4. Walid Toumi says:


    here some variant:

    PS II> [regex]::ismatch($a,"m")


    PS II> Select-String -InputObject $a -Pattern m -Quiet -SimpleMatch


    PS II> $a -replace 'm' -ne $a


  5. Walid Toumi says:

    another variant:

    PS II> $a.ToCharArray() -contains 'm'


    PS II> 'm' in $a.ToCharArray()   #PS3


  6. Ed Wilson says:

    @K_Schulte I am glad you add additional suggestions. I am not posting "edicts" here, but am really wanting to get a conversation started. Everyone who does PowerShell for more than a few months ends up doing things their favorite way. I am hoping to show other ways of doing things, so that we can add an additional tool in our box of tricks. Thank you for sharing.

  7. Ed Wilson says:

    @Walid Toumi Those are great additions. Thank you for sharing.

  8. Ed Wilson says:

    @JRV we quit doing Sesame Script years ago … 🙂

Skip to main content