fbpx Trim a String in Windows PowerShell | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Trim a String in Windows PowerShell

Problem

You want to remove leading or trailing spaces from a string or user input.

Solution

Use the Trim() method of the string to remove all leading and trailing whitespace characters from that string.

PS >$text = " `t Test String`t `t" PS >"|" + $text.Trim() + "|" |Test String|

Discussion

The Trim() method cleans all whitespace from the beginning and end of a string. If you want just one or the other, you can also call the TrimStart() or TrimEnd() method to remove whitespace from the beginning or the end of the string, respectively. If you want to remove specific characters from the beginning or end of a string, the Trim(), TrimStart(), and TrimEnd() methods provide options to support that. To trim a list of specific characters from the end of a string, provide that list to the method, as shown in Example 55.

Example 55. Trimming a list of characters from the end of a string

PS >"Hello World".TrimEnd('d','l','r','o','W',' ') He

At first blush, the following command that attempts to trim the text "World" from the end of a string appears to work incorrectly:

PS >"Hello World".TrimEnd(" World")

He This happens because the TrimEnd() method takes a list of characters to remove from the end of a string. PowerShell automatically converts a string to a list of characters if required, so this command is in fact the same as the command in Example 55.

If you want to replace text anywhere in a string (and not just from the beginning or end)

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say