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('*'

Command Line Expert & Software Engineer
Welcome! I’m Thomas Heinrich, a software engineer and system administrator with a deep passion for the Command Line Interface (CLI). With years of experience navigating the terminal, building backend architectures, and automating server deployments, I created this space to share practical, real-world terminal knowledge.
Whether you are a beginner taking your first steps in a Linux environment or a seasoned DevOps engineer looking to optimize your deployment scripts, you will find actionable solutions here. My goal is to help you ditch the mouse, speed up your workflow, and harness the full power of the command line.