Creating Leading Zeros

by Oct 20, 2017

Did you ever need to convert numbers into strings with leading zeros, for example to compose server names? Simply use PowerShell’s “-f” operator:

$id = 12
'server{0:d4}' -f $id

Here is the output:

 
server0012
 

The –f operator expects a text template on its left side, and value(s) on its right side. Inside the text template, use {x} as placeholder(s) for your values on the right side. Placeholders start with index 0.

To add leading zeros, use “d” (short for “digit”) followed by the number of digits you require.

Twitter This Tip! ReTweet this Tip!