PowerShell String Methods: Trim, ToUpper, Contains, and More

PowerShell strings are .NET System.String objects, which means every string you create in PowerShell automatically has access to the full .NET string API. You don’t need to import anything — just call the method directly on the string. This guide covers the most useful PowerShell string methods: trimming whitespace, changing case, checking content, extracting substrings, padding for alignment, and formatting output with the -f operator.
Trim, TrimStart, TrimEnd
Whitespace removal is one of the most common string operations, especially when processing user input or file data:
$raw = ' hello world '
# Remove leading and trailing whitespace
$raw.Trim() # 'hello world'
# Remove only leading whitespace
$raw.TrimStart() # 'hello world '
# Remove only trailing whitespace
$raw.TrimEnd() # ' hello world'
# Trim specific characters
'***config***'.Trim('*') # 'config'
'C:\Logs\'.TrimEnd('\') # 'C:\Logs'
hello world
hello world
hello world
config
C:\Logs
Trim(), TrimStart(), and TrimEnd() also accept a character array to remove specific characters from the edges. This is useful for stripping path separators, punctuation, or padding characters.
ToUpper and ToLower
Case conversion is straightforward with these two methods:
$username = 'Alice.Smith'
$username.ToUpper() # ALICE.SMITH
$username.ToLower() # alice.smith
# Practical use: normalize for comparison
$input = 'YES'
if ($input.ToLower() -eq 'yes') {
Write-Output 'User confirmed'
}
ALICE.SMITH
alice.smith
User confirmed
In practice, for comparisons it’s often cleaner to use PowerShell’s built-in case-insensitive operators like -eq (which is already case-insensitive) rather than converting case manually. Use ToUpper() and ToLower() when you need a consistently cased output for display or storage.
Contains, StartsWith, EndsWith
These three methods check string content and return a boolean. Important: all three are case-sensitive by default:
$filename = 'AppLog_2026-05-04.txt'
# Case-sensitive checks
$filename.Contains('AppLog') # True
$filename.Contains('applog') # False
$filename.StartsWith('AppLog') # True
$filename.EndsWith('.txt') # True
$filename.EndsWith('.log') # False
# For case-insensitive checking, use PowerShell's -like operator instead
$filename -like '*applog*' # True (case-insensitive)
True
False
True
True
False
True
When case sensitivity matters and you want a method-based approach, pass [StringComparison]::OrdinalIgnoreCase as the second argument: $str.Contains('text', [StringComparison]::OrdinalIgnoreCase). This requires PowerShell 7+ or .NET 5+.
Substring and IndexOf
Substring(startIndex, length) extracts a portion of a string. IndexOf() finds where a character or substring first appears:
$url = 'https://api.example.com/v2/users'
# Find where the path starts
$pathStart = $url.IndexOf('/', 8) # Skip past 'https://'
$path = $url.Substring($pathStart)
$path # /v2/users
# Extract a fixed-length field
'2026-05-04'.Substring(0, 4) # 2026 (year)
'2026-05-04'.Substring(5, 2) # 05 (month)
# LastIndexOf — find the last occurrence
$filePath = 'C:\Logs\Archive\app.log'
$lastSlash = $filePath.LastIndexOf('\')
$filename = $filePath.Substring($lastSlash + 1)
$filename # app.log
/v2/users
2026
05
app.log
If Substring() arguments are out of range (start index >= length, or length extends past the end), it throws ArgumentOutOfRangeException. Always validate the index with IndexOf() first (which returns -1 if not found) before using it in Substring().
PadLeft and PadRight
These methods pad a string to a specified total width, useful for aligned output and fixed-width formatting:
# Right-align numbers in a report
$items = @(1, 12, 123, 1234)
foreach ($n in $items) {
[string]$n.PadLeft(6)
}
# Zero-pad a number
$id = 42
[string]$id.PadLeft(6, '0') # 000042
# Left-align strings
'Name'.PadRight(20) + 'Value'
'Alice'.PadRight(20) + '42'
1
12
123
1234
000042
Name Value
Alice 42
Format Strings with -f Operator
The -f operator is PowerShell’s composite formatting, equivalent to String.Format() in .NET. It’s great for tabular output and number formatting:
# Basic positional formatting
'Server: {0}, Port: {1}' -f 'web01', 443
# Number formatting
'CPU: {0:P1}' -f 0.876 # Percentage: CPU: 87.6%
'Size: {0:N2} MB' -f 1536.7 # Numeric: Size: 1,536.70 MB
'ID: {0:D6}' -f 42 # Decimal padded: ID: 000042
# Date formatting
'Report date: {0:yyyy-MM-dd}' -f (Get-Date)
Server: web01, Port: 443
CPU: 87.6%
Size: 1,536.70 MB
ID: 000042
Report date: 2026-05-04
The -f operator supports the full range of .NET format specifiers, making it more powerful than simple string interpolation for numeric and date formatting.
Common Errors and Fixes
-
Contains is case-sensitive — use -like for case-insensitive:
'AppLog'.Contains('applog')returnsFalse. Use PowerShell’s-like '*applog*'operator for case-insensitive pattern matching, or-match 'applog'for regex matching (both are case-insensitive by default in PowerShell). -
Substring index out of range on short strings: If
IndexOf()returns-1(not found), using that as aSubstring()start index throws an exception. Always guard:if ($idx -ge 0) { $str.Substring($idx) }.
Related Cmdlets / See Also
Wrapping Up
PowerShell string methods give you the full .NET string toolkit without importing anything. Use Trim() for whitespace cleanup, Contains()/StartsWith()/EndsWith() for content checks, Substring() with IndexOf() for extraction, and -f for formatted output. Remember that Contains() is case-sensitive — use -like when you need case-insensitive matching. Your next step: apply the -f operator to format a table report from your own data.


