Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

powershell - create subdir struct adding a zero on single digit months

Tags:

powershell

i'm super new to powershell.

attempting to create a basic directory structure yyyy/mm

what it creates:

C:\2020
├───1
├───10
├───11
├───12
├───2
├───3
├───4
├───5
├───6
├───7
├───8
└───9

i'm trying to add a zero to months jan = 01...september 09. oct = 10, nov = 11, dec = 12

desired result:

C:\2020
├───01
├───02
├───03
├───04
├───05
├───06
├───07
├───08
├───09
├───10
├───11
└───12

this is the nested loop i have. any inputs are appreciated. thank you in advance

      for ($i=2020; $i -le 2022;$i++) #years from 2020 to 2022
            { 
                for ($j=01; $j -le 12;$j++) # for months eg 01-12
                    {
                        New-Item -ItemType Directory -Path $path\$i\$j -Force
                    }
            }    
like image 674
user2585000 Avatar asked Aug 11 '26 14:08

user2585000


1 Answers

You can use the format operator to add leading zeros. See https://ss64.com/ps/syntax-f-operator.html

2020..2022 | % {
    $year = $_
    1..12 | % {
        $month = "{0:d2}" -f $_
        New-Item -ItemType Directory -Path "$path\$year\$month" -Force
    }
}
like image 108
Jacob Colvin Avatar answered Aug 13 '26 13:08

Jacob Colvin