PowerTip: Remove Leading and Trailing Spaces with PowerShell

Summary: Use the Trim() method to remove extraneous space from a String object.

Hey, Scripting Guy! Question Is there an easy way to drop all spaces that are before or after a string in Windows PowerShell?

Hey, Scripting Guy! Answer Use the Trim() method to remove all spaces before and after a string from the output, for example:

$Something='                 I love PowerShell                     '


Comments (2)

  1. Rob Pfeiffer says:

    To change the value of $Something you need to use $Something = $Something.Trim()

    The function itself will just output the trimmed value but does not change it. This is important if you later want to evaluate the trimmed contents – If ($Something -match “love PowerShell”) { Do something else }

Skip to main content