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.

2 thoughts on “Fun with PowerShell – Formatting Numbers

  1. Hi, I know this is an old post but I am trying to achieve 2 digit formatting when renaming files using Powershell. I have the files being renamed correctly except that I need the format to be 123456-01 then 123456-02 With the command below I am achieving 123456 1 and 123456 2 How do I add your {0:D2} into this. I have tried various places without success. The second question is how to get it to start at 00 and increment from there. Any help you can provide is greatly appreciated.

    $rename = Get-ChildItem “$PSScriptRoot\rename”

    $i = 1
    foreach ($file in $rename){
    $newname = “123456 $i – ” + $file
    Rename-Item $($file.FullName) $newname
    $i++}

    • Hi Susan, does something like the following work for you?:
      $rename = Get-ChildItem “$PSScriptRoot\temp\rename”

      $i = 1
      foreach ($file in $rename){
      $x = “{0:D2}” -f $i
      $newname = “123456-$x – ” + $file
      Rename-Item $($file.FullName) $newname
      $i++}

Leave a Reply to susan Cancel reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.