PowerTip: Return Specific Number of Letters from String


Summary: Use Windows PowerShell to return a specific number of letters from a string.

Hey, Scripting Guy! Question How can I use Windows PowerShell to easily to retrieve the first two letters from a string?

Hey, Scripting Guy! Answer Use the SubString method from a string, and then specify the starting the position and the number
           of letters to return, for example:

PS C:\> ("string").Substring(0,2)

st

Comments (2)

  1. thomas says:

    "SubString method" should be "Substring method"

  2. doubting thomas says:

    > "SubString method" should be "Substring method"

    This would be relevant if powershell was case sensitive – this is not C, perl, or other languages that care.

    All of these work, whatever floats your boat. Don’t be picky. I am more likely to use all lowercase because if I don’t have to mix case, why waste the effort pressing extra keys? There’s no specific right or wrong use if it works and does what you need. Claiming
    a reference to a technical document as the original reference and the only right way has no value.
    ("string").substring(0,2)
    ("string").Substring(0,2)
    ("string").SubString(0,2)
    ("string").subString(0,2)
    ("string").SUBSTRING(0,2)
    ("string").SuBsTrInG(0,2)

Skip to main content