PowerTip: Determine Letter a String Begins With


Summary: Use Windows PowerShell to determine the letter that a string begins with.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find if a particular string begins with the letter “s”?

Hey, Scripting Guy! Answer Use the StartsWith method from the string, for example:

PS C:\> "string".StartsWith("S")

False

PS C:\> "string".StartsWith("s")

True

Note The StartsWith method is case sensitive. Therefore “S” does not match the example, but “s” does.

Comments (4)

  1. David Wyatt says:

    Another way of avoiding the case sensitivity is to use PowerShell’s operators instead of a .NET method:

    "string"[0] -eq ‘S’

    or

    "string" -like ‘S*’

    or

    "string" -match ‘^S’

  2. romeo donca says:

    Just one remark

    To avoid case sensitive,

    "string".ToLower().StartsWith("s")
    or
    "string".ToUpper().StartsWith("S")

  3. Chen V says:

    Thanks Ed! Nice tip.

Skip to main content