Remove Spaces From a Variable Using PowerShell

  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

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.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - PowerShell String

  • Selecting Multiple Patterns in a String Using PowerShell
  • Convert a Secure String to Plain Text in PowerShell
  • Check if a String Is Not NULL or EMPTY