Remove Spaces From a Variable Using PowerShell

Rohan Timalsina Dec 21, 2022 Apr 30, 2022
  1. Use the Replace Operator to Remove Spaces From a Variable Input Using PowerShell
  2. Use the Replace() Method to Remove Spaces From a Variable Input Using PowerShell
  3. Use the Trim() Method to Remove Spaces From a Variable Input Using PowerShell
Remove Spaces From a Variable Using PowerShell

A string is one of the most common data types used in PowerShell. It contains the sequence of characters or texts.

The PowerShell string has the System.String object type. A string is defined by using single or double quotes in PowerShell.

You can perform different string operations in PowerShell, such as replacing strings, concatenating strings, splitting strings, comparing strings, and extracting substrings.

This tutorial will teach you to remove spaces from a variable by replacing them with an empty string in PowerShell.

Use the Replace Operator to Remove Spaces From a Variable Input Using PowerShell

The -Replace operator replaces texts or characters in PowerShell. You can also use it to remove texts or characters from the string.

The -Replace operator takes two arguments: the string to find and the string to replace from the given input.

This is our string variable $string.

$string = "Power Shell"

To remove all spaces from the string, you can run the command below.

$string -replace " ",""

Output:

PowerShell

In the above command, the -Replace operator finds all space characters " " and replaces them with an empty string "".

Use the Replace() Method to Remove Spaces From a Variable Input Using PowerShell

The Replace() method is similar to the -Replace operator. It also takes two arguments: the string to find and the string to replace.

In the following example, the Replace() method finds all space characters " " and replaces them with an empty string "".

$string = "P o w e r S h e l l"
$string.replace(" ","")

Output:

PowerShell

Use the Trim() Method to Remove Spaces From a Variable Input Using PowerShell

Another way to remove spaces from strings is the Trim() method of the System.String .NET class. It allows you to remove all whitespaces or unwanted characters from the front and end of strings.

For example, the following command trims the leading and trailing white space characters from the given string object.

$string = "  PowerShell String  "
$string.Trim()

Output:

PowerShell String

TrimStart() method removes characters from the beginning of the strings, whereas TrimEnd() removes characters from the end of the strings.

We hope this article helped you remove spaces from a string variable in PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell String