PowerTip: Remove Spaces from Both Ends of String


Summary: Learn to use Windows PowerShell to remove spaces from both ends of a string.

Hey, Scripting Guy! Question How can I use Windows PowerShell to remove spaces at both ends of a string?

Hey, Scripting Guy! Answer Use the Trim method from the System.String .NET Framework class. 
          In this example, I create a string with a space at each end of the word, then
          I call the Trim method to remove both spaces:

$string = " a String "

$string.Trim()

Note  The Trim method exists on strings, so to use it, simply call it directly from the string. 

Comments (3)

  1. tommymaynard says:

    In most cases, it looks like the regex option is slower than the Trim method. Of course, we’re talking about ticks – a unit of time smaller than milliseconds.

    $String = " a String "

    Write-Output -Verbose "`r`nUsing Trim Method (Ticks)"
    for ($j = 0; $j -le 10; $j++) {
    $MeasureTime = Measure-Command {$String.trim()}
    If ($MeasureTime.Milliseconds -ge 0) {
    Write-Output -Verbose $MeasureTime.Ticks
    } Else {
    Write-Output -Verbose ‘Greater than 1 millisecond’
    }
    }

    Remove-Variable -Name MeasureTime

    Write-Output -Verbose "`r`nUsing Regex (Ticks)"
    for ($i = 0; $i -le 10; $i++) {
    $MeasureTime = Measure-Command {$String -replace ‘^s+|s+$’}
    If ($MeasureTime.Milliseconds -ge 0) {
    Write-Output -Verbose $MeasureTime.Ticks
    } Else {
    Write-Output -Verbose ‘Greater than 1 millisecond’
    }
    }

    Remove-Variable -Name i,j -ErrorAction SilentlyContinue

  2. walid toumi says:

    another option:

    PS> $string -replace ‘^s+|s+$’

Skip to main content