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)