PowerTip: Determine What Character a String Starts With

Summary: Use Windows PowerShell to determine what character a string starts with.

Hey, Scripting Guy! Question How can I use Windows PowerShell to show me if a string starts with a particular letter (this also needs to be
           case sensitive)?

Hey, Scripting Guy! Answer Use the StartsWith method from the String class, and supply the character to the method. It will return
           a True or False Boolean value, for example:

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


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


Comments (9)

  1. mmuffins says:

    Are there any advantages to using this over

    "string".substring(0,1) -ceq "s"

    apart from being shorter? It appears to be much more situational than using substring.

  2. Per Møller says:

    Another way of achieving the same could be done like this.

    "string" -clike "s*"
    "string" -cmatch "^s"

    Then if you don’t want case sensitivity you could just use normal -like and -match respectively.

  3. Ed Wilson says:

    @mmuffins the -ceq is case sensitive. Also when using the equality operator like you did here, it will match any lower case s in the word. The StartsWith matchs at the beginning of a string. @Per you are correct your two operators are the same.

  4. allanm says:

    Really not my place to correct the famed Scripting Guy 🙂 but …

    The subject and the tip don’t really match. If the subject was "determine if a string starts with a specific character", it would be correct. Using .startswith is testing if the string starts with a specific character.

    For determine what character a string starts with, one of probably many ways would be e.g.

    I know, I’m nit-picky, my wife tells me that all the time.

  5. allanm says:

    The other way I test the first character(s) depending what I am doing is with regex:

    $env:COMPUTERNAME -match "^f"

  6. mukesh-kumar says:

    I would test the first character of a string using the regex :
    $env:COMPUTERNAME -match "^w"

  7. allanm says:

    True mukesh-kumar – but all ^w tells me is that the first character is a "word" character. It doesn’t tell me what it is.

    It can be useful at times just to validate that a string does start with alpha-numeric / word characters but not testing if a string contains or starts with a specific value.

  8. mukesh-kumar says:

    allanm, $Matches variable will give the first character of the string.

  9. allanm says:

    Oh! Thanks, that one is new to me, I had never seen it before. Not as obvious as simply grabbing the first character with substring or a specific character, but you’re right, and that could be useful at times.

Skip to main content