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 = '                    steve'

The length of the variable $twentyWhitespaces is 25 – 5 (steve) = 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 = 'steve'.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)

padleft-method-char-powershell

Note: The PadRight() method is also available.


previous-buttonnext-button

One thought on “Don’t do that #25: Manually add whitespaces for padding strings

  1. Pingback: Don’t do that #24: Use Get-QADUser (Quest) to receive AllMemberOf of a user | Powershell Guru

Leave a Reply

Your email address will not be published. Required fields are marked *