PowerTip: Remove trailing space from a string by using PowerShell


Summary: Use the trim() method to remove leading and trailing spaces from a string.

Hey, Scripting Guy! Question Could you do me a huge favor and show me how to get rid of spaces before and after a string in PowerShell?

Hey, Scripting Guy! Answer No problem at all. All you need to do is apply the trim() method to remove all the output. You can also use trimstart() to remove the start or trimend() to remove the end. Here is an example:

$Data=’           Look at all of this wasted space on my screen.
$Data
$Data.trim()
$Data.trimstart()
$Data.trimend()

The Doctor

Comments (2)

  1. Dale Thompson says:

    $Data -replace ‘\s+\z’
    $Data -replace ‘\A\s+’
    $Data -replace ‘A\s*(.*?)\s*\z’, ‘$1’

  2. @Dale Thompson

    Thanks for sharing the Regex trick. A wonderful and powerful tool.

    I love it with PowerShell, often so many options to provide the same answer, so many tools to choose from.

    Well played 🙂

    Sean
    Honorary Scripting Guy

Skip to main content