Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

5.12 Trim a String

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 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 5-7.

Example 5-7. Trimming a list of characters from the end of a string
PS > "Hello World".TrimEnd('d','l','r','o','W',' ')
He

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

Note

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, and in this case converts your string to the characters W, o, r, l, d, and a space. These are in fact the same characters as were used in Example 5-7, so it has the same effect.

See Also

Recipe 5.8, “Replace Text in a String”