Monthly Archive

Categories

PowerShell Trim

PowerShell Trim – no its not a new slimming fad. Trimming is the act of removing characters – usually white space – from the beginning or end of a string.

You have three methods on the String class you can use

Trim
TrimEnd
TrimStart

 

PS> $str = "   abcdefghijk   "
PS> $str.TrimStart()
abcdefghijk
PS> $str.TrimEnd()
abcdefghijk
PS> $str.Trim()
abcdefghijk

 

You can also trim specific characters from the beginning or end of a string

PS> $str = ".,:abcdefghijk:,."

PS> $tc = [char]'.', [char]',', [char]':'

 

PS> $str.TrimStart($tc)
abcdefghijk:,.
PS> $str.TrimEnd($tc)
.,:abcdefghijk
PS> $str.Trim($tc)
abcdefghijk

 

You should now be able to handling any string trimming required in your code

Comments are closed.