Don’t do that #25: Manually add whitespaces for padding strings

By | April 24, 2015

Don’t do that: You want to add exactly 20 whitespaces on the left side of a string :

$twentyWhitespaces = '                    test'

The length of the variable $twentyWhitespaces is 25 – 5 (test) = 20 whitespaces

whitespaces powershell

Do that: The above code works well but it is definitely not practical to manually count the number of whitespaces to add and human errors can occur.

In the String class, there is a .NET method PadLeft() which can be useful in this case:

$padLeft = 'test'.PadLeft(25)

We get the same results with less effort and more reliability:

padleft method powershell

It is possible to replace the whitespace by a character: PadLeft(Int32, Char)


Note: The PadRight() method is also available.


Leave a Reply

Your email address will not be published.