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

Tachytelic.net

  • Sco Openserver
    • Sco Unix Support
    • SCO Openserver Installation ISOs
    • SCO Openserver Binaries
    • Add a Hard Drive to an Openserver 5 Virtual Machine
    • Install SCO Vision SQL-Retriever ODBC Driver on Windows 10
    • License Expired on Virtual SCO Openserver Installation
    • How to reset the root password on SCO Openserver 5
  • Scripting
    • PowerShell
      • Add leading zeros
      • Check if a File Exists
      • Grep with Powershell
      • Create Environment Variables
      • Test for open Ports
      • Append to a Text File
    • VBScript
      • Check if a File Exists
      • lpad and rpad functions
      • Windows Update E-Mail Notification
  • Office 365
    • Connect to Office 365 with PowerShell
    • Add or remove an email alias using Powershell
    • Change Primary email address of Active Directory user
    • How to hide an AD user from the Global Address List
    • How to hide mail contacts from the Global Address List
    • Change the primary email address for an account with PowerShell
    • Change Primary email address of an AD User
    • Grant a single user access to access to all calendars
    • Forward email to an external address using Powershell
    • Convert shared mailbox to user mailbox with Powershell
  • Get in Touch
  • About Me
    • Privacy Policy

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

Related

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
Go to mobile version