When you need a little extra padding. A short story about .padleft() and .padright()

Today, I found myself with a small dilemma. I needed to do a user data extract from Active Directory, massage the data a bit, spit out a CSV, and the upload the CSV to a piece of software we use. Easy, simple, no problem….until the software wasn’t putting people into the places they were supposed to go. Damn it!

After a little trouble shooting, we figured out that the field we were pulling from AD (the “office” field) to sort people in the software, would not accept anything with a single digit. So for example offices 20, 33, and 23 would get sorted perfectly fine. Anything with a single digit like offices 3, 5, and 7, would not get sorted.

Basically, I needed to pad anything that was only one character, by putting a zero in front of it. So an office number like “2” would become “02”. Powershell makes this really easy to do . For example:

1
2
3
$office_number = "2"
$padded_office_number = $office_number.Padleft(2, "0")
$padded_office_number

Easy peasy.

So, breaking down the .padleft(2, “0”) a bit. The first number in the parenthesis, the number 2, is how far you want to pad out to the left, and the zero in the quotes in my example, is the character you want to pad with. It could be any character, not just a number.

.padright() works exactly the same as .padleft()

Leave a Reply

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