🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell String Methods

A string method is a built-in action you can run on a string. A method changes or inspects the text and gives back a result.

Change the letter case

ToUpper returns all capital letters. ToLower returns all small letters.

$word = "PowerShell"
$word.ToUpper()
$word.ToLower()

Trim spaces and replace text

Trim removes spaces from both ends. Replace swaps one piece of text for another.

"  Ana  ".Trim()
"a-b-c".Replace("-", "+")

Take part of a string

Substring takes a starting position and a length. Positions start at zero.

$word = "PowerShell"
$word.Substring(0, 5)
$word.Substring(5)

Example

$raw = "  ana lee  "
$clean = $raw.Trim()
$clean
$clean.ToUpper()
$clean.Replace(" ", "-")

Key points

  • Method: a built-in action that runs on a value.
  • Call: write a dot and the method name after the string, with parentheses.
  • ToUpper: the ToUpper method returns the string in all capital letters.
  • ToLower: the ToLower method returns the string in all small letters.
  • Trim: the Trim method removes spaces from both ends of a string.
  • Replace: the Replace method swaps one piece of text for another piece.
  • Substring: the Substring method returns part of a string by position.

In this example, the first line stores a name with extra spaces. The second line trims those spaces away. The last three lines print the clean name, its capital-letter form, and its hyphenated form.

Note

the Contains method is case-sensitive. It only matches the exact capital letters you type.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does "PowerShell".ToLower() return?