Skip to main content
not a substringUnderstand that .Trim('abc') removes any combination of 'a'

Trim In PowerShell: CLI Command Reference, Syntax, Flags

trim in powershell is the .NET String.Trim() method that removes leading and trailing whitespace or specified characters. It includes TrimStart() and TrimEnd() variants for targeted removal.

# Basic syntax
$string.Trim()
$string.Trim([char[]]$CharactersToRemove)
$string.TrimStart([char[]]$CharactersToRemove)
$string.TrimEnd([char[]]$CharactersToRemove)

# Alternative using -replace regex
$string -replace '^s+|s+$'   # trim whitespace
$string -replace '^[chars]+|[chars]+$'  # trim specific chars

Tested on Windows PowerShell 5.1 and PowerShell 7.4 (cross-platform).

Syntax

Full syntax from official docs: .Trim([ Characters_to_remove ]), .TrimEnd([ Characters_to_remove ]), .TrimStart([ Characters_to_remove ]). If Characters_to_remove is omitted, whitespace is removed. Multiple characters can be specified; order does not affect result.

Options and Flags

Parameter / Method Type Default Description
.Trim() Method Whitespace Removes all Unicode whitespace from both ends (spaces, tabs, newlines, etc.)
.Trim([char[]]) Method N/A Removes any characters present in the array from both ends. Order ignored.
.TrimStart([char[]]) Method Whitespace Same as Trim() but only from the start of the string.
.TrimEnd([char[]]) Method Whitespace Same as Trim() but only from the end of the string.
-replace operator Operator N/A Supports regex patterns like '^s+|s+$' for advanced trimming; not a method but commonly used.

Usage Examples

Example 1: Remove leading/trailing whitespace from user input

$userInput = "   John Doe   "
$clean = $userInput.Trim()
Write-Output "'$clean'"   # Output: 'John Doe'

Default .Trim() removes all Unicode whitespace from both ends — the most common sanitization before comparisons or storage.

Example 2: Remove trailing backslashes from a directory path

$path = "C:UsersAdminDocuments"
$normalized = $path.TrimEnd('')
Write-Output $normalized   # Output: C:UsersAdminDocuments

Trailing backslashes break path concatenation; .TrimEnd('') removes only trailing while preserving the path structure.

Example 3: Trim multiple characters from both ends

$text = ""***Alert*** System overload! ***""
$cleaned = $text.Trim('*'