Removing spaces from a variable input using PowerShell 4.0 Removing spaces from a variable input using PowerShell 4.0 powershell powershell

Removing spaces from a variable input using PowerShell 4.0


The Replace operator means Replace something with something else; do not be confused with removal functionality.

Also you should send the result processed by the operator to a variable or to another operator. Neither .Replace(), nor -replace modifies the original variable.

To remove all spaces, use 'Replace any space symbol with empty string'

$string = $string -replace '\s',''

To remove all spaces at the beginning and end of the line, and replace all double-and-more-spaces or tab symbols to spacebar symbol, use

$string = $string -replace '(^\s+|\s+$)','' -replace '\s+',' '

or the more native System.String method

$string = $string.Trim()

Regexp is preferred, because ' ' means only 'spacebar' symbol, and '\s' means 'spacebar, tab and other space symbols'. Note that $string.Replace() does 'Normal' replace, and $string -replace does RegEx replace, which is more heavy but more functional.

Note that RegEx have some special symbols like dot (.), braces ([]()), slashes (\), hats (^), mathematical signs (+-) or dollar signs ($) that need do be escaped. ( 'my.space.com' -replace '\.','-' => 'my-space-com'. A dollar sign with a number (ex $1) must be used on a right part with care

'2033' -replace '(\d+)',$( 'Data: $1')Data: 2033

UPDATE: You can also use $str = $str.Trim(), along with TrimEnd() and TrimStart(). Read more at System.String MSDN page.


You're close. You can strip the whitespace by using the replace method like this:

$answer.replace(' ','')

There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).


You also have the Trim, TrimEnd and TrimStart methods of the System.String class. The trim method will strip whitespace (with a couple of Unicode quirks) from the leading and trailing portion of the string while allowing you to optionally specify the characters to remove.

#Note there are spaces at the beginning and endWrite-Host " ! This is a test string !%^ " ! This is a test string !%^#Strips standard whitespaceWrite-Host " ! This is a test string !%^ ".Trim()! This is a test string !%^#Strips the characters I specifiedWrite-Host " ! This is a test string !%^ ".Trim('!',' ')This is a test string !%^#Now removing ^ as wellWrite-Host " ! This is a test string !%^ ".Trim('!',' ','^')This is a test string !%Write-Host " ! This is a test string !%^ ".Trim('!',' ','^','%')This is a test string#Powershell even casts strings to character arrays for youWrite-Host " ! This is a test string !%^ ".Trim('! ^%')This is a test string

TrimStart and TrimEnd work the same way just only trimming the start or end of the string.