Fun with PowerShell – Formatting Numbers

Recently, I had the need to develop a consistent numbering format in order to maintain character length and ordering for collection names in ConfigMgr.  The basic idea was to create 31 collections, each that have the number in the name a keeping all of them to two digits.  So, for the numbers less than ten, adding a leading zero will maintain this two digit format.  Luckily, this is very easy to do inside PowerShell using the .NET formatting methods.

Starting with the number 1, we can format this as 01 using the following command:

“{0:D2}” -f 1

Create a quick loop from 1 to 10 and you see that you have a nicely formatted two digit output:

for ($x=1; $x -le 10; $x++){
#Format the number as two digits
"{0:D2}" -f $x

This can be expanded to the number of digits that are required. Also, there are other format types as well: C is for currency, P is for percentage and X is for hexadecimal.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.