Adding Leading Zeroes

by Jun 21, 2018

If you need numbers with leading zeroes, for example for server names, here are two approaches. First, you can turn the number into a string, then use PadLeft() to “pad” the string to the desired length:

$number = 76
$leadingZeroes = 8

$number.Tostring().PadLeft($leadingZeroes, '0') 

Or, you can use the -f operator:

$number = 76
$leadingZeroes = 8

"{0:d$leadingZeroes}" -f $number

Twitter This Tip! ReTweet this Tip!