• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Tachytelic.net

  • Get in Touch
  • About Me

How to Format a variable with leading zeros in Powershell

May 23, 2019 by Paulie 1 Comment

If you need to format a number in Powershell to include leading zeros, so that the length is always a fixed width, it is easy to do with Powershell format operator.

I was working with some data that stored dates as single digits for those days and months that only contained a single digit. For example I needed “1/1/2019” to be “01/01/2019”.

Using the powershell “-f” operator it is easy to add the leading zeros. For example:

PS C:\> "{0:d2}/{1:d2}/{2:d4}" -f 1,1,2019
01/01/2019

You can easily wrap this in a loop like this:

foreach ($months in @(1..12)) 
{
    $Month = "{0:d2}" -f $months
    foreach ($days in @(1..31))
    {
        $Day = "{0:d2}" -f $days
        $ArchiveFolder =  "D:\Archive\PDF\2019\$month\$day"
        Write-Host $ArchiveFolder
    }
    
}

Image of PowerShell loop padding a single digit number with leading zeros

Filed Under: Scripts & Utilities Tagged With: Powershell

Reader Interactions

Trackbacks

  1. Two functions to easily left pad or right pad strings with vbscript says:
    May 23, 2019 at 11:02 am

    […] pad with VBScript. But these small functions make it simple. I’ve also written up how to do padding with Powershell, which makes things much […]

Leave a Reply Cancel reply

Primary Sidebar

Link to my LinkedIn Profile
Buy me a coffee

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 254 other subscribers.

Go to mobile version