There are many different ways to add leading zeros to a number in PowerShell. In practice, numbers (object type: [int]) cannot have leading zeros, so we are really creating a text value (object type: [string]) that contains the number.
In the examples below, I pad the number 42 to four digits (0042). Of course, you can adjust the length of the padding as needed :)
I also demonstrate the following options (and a few more) in this video on YouTube.
With the format operator
My personal favorite is the format operator -f:
| |
If you want to generate a computer name with a fixed length, for example, you could do something like this:
| |
The format operator can do more. For a first overview, I recommend this page on SS64.com.
[int].ToString() method
Another option is to use the .ToString() method of an [int] object:
| |
[String].PadLeft() method
This might also be useful in some scenarios: the .PadLeft() method of a [String] object. Since we start here with a number [int], we first convert it to a string using ToString(). It would also be possible to add the zeros during the string conversion itself (see section [int].ToString() method), but I still find it interesting to mention .PadLeft(). Perhaps you can use it for something else.
| |
If you ever want to pad with characters on the right, there is also .PadRight():
| |