0
0
PowershellHow-ToBeginner · 3 min read

How to Use String Operations in PowerShell: Syntax and Examples

In PowerShell, you use string methods like .ToUpper(), .Substring(), and operators like -like or -replace to manipulate strings. You can call methods directly on string variables or use operators for pattern matching and replacement.
📐

Syntax

PowerShell strings are objects with built-in methods and support operators for common tasks.

  • Method call: $string.MethodName() - calls a method on the string.
  • Operators: -like, -match, -replace - perform pattern matching and replacement.
  • Concatenation: Use + or string interpolation "Hello $name".
powershell
$string = "Hello World"
$string.ToUpper()
$string.Substring(0,5)
"Hello " + "PowerShell"
"Hello $string"
Output
HELLO WORLD Hello Hello PowerShell Hello Hello World
💻

Example

This example shows how to convert a string to uppercase, extract a part, replace text, and check if it contains a word.

powershell
$text = "PowerShell is fun"

# Convert to uppercase
$upper = $text.ToUpper()

# Extract substring
$part = $text.Substring(0,9)

# Replace text
$replaced = $text -replace "fun", "awesome"

# Check if contains 'Shell'
$contains = $text -like "*Shell*"

# Output results
$upper
$part
$replaced
$contains
Output
POWERSHELL IS FUN PowerShell PowerShell is awesome True
⚠️

Common Pitfalls

Common mistakes include confusing operators and methods, or forgetting strings are case-sensitive by default.

  • Using -like for exact matches instead of -eq.
  • Not using wildcards * with -like.
  • Trying to modify strings directly (strings are immutable).
powershell
# Wrong: exact match with -like
"Hello" -like "Hello" # works but exact match better with -eq

# Right: use -eq for exact match
"Hello" -eq "Hello"

# Wrong: no wildcard with -like
"Hello World" -like "World"

# Right: use wildcard
"Hello World" -like "*World*"
Output
True True False True
📊

Quick Reference

OperationSyntaxDescription
Convert to uppercase$string.ToUpper()Returns string in uppercase
Extract substring$string.Substring(start, length)Returns part of string
Replace text$string -replace 'old', 'new'Replaces text using regex
Check pattern$string -like '*pattern*'Checks if string matches wildcard pattern
Concatenate"Hello " + $nameJoins strings together
String interpolation"Hello $name"Inserts variable values into string

Key Takeaways

Use string methods like .ToUpper() and .Substring() to manipulate strings directly.
Use operators like -like and -replace for pattern matching and text replacement.
Remember strings are immutable; methods return new strings, they do not change the original.
Use wildcards (*) with -like for flexible pattern matching.
String interpolation with double quotes is an easy way to combine text and variables.