Home > Software engineering >  how to create monthly folder from 2020 to 2024 in powershell
how to create monthly folder from 2020 to 2024 in powershell

Time:06-06

I need to auto create monthly folder from 2020 to 2024.

For instance,

  • 2020

     -Jan
     -Feb
      ...
     -Dec
    
  • 2021

     -Jan
      ...
     -Dec
    
  • 2022

     -Jan
     ...
     -Dec
    

all the way to 2024.

I have tried with my code -

$d = 1..12|%{(get-date).AddMonths(-6 $_).ToString("MMM yyyy")} 
$d | % {(new-Item -Path C:\testmonth\$_ -ItemType Directory)}

I want to know is there a better coding to auto create monthly folder.

Much appreciated folks

CodePudding user response:

First, you need to loop the years as well. So get all the years.

$y = 1..4 | ForEach-Object { (get-date).AddYears(-1 $_).ToString("yyyy") }

Excuse my compulsion to change % = ForEach-Object. You are welcome to change it back.

Then get the months as you did.

$d = 1..12| ForEach-Object { (get-date).AddMonths(-6 $_).ToString("MMM") } 

Now you need to loop the years and the months. The trick is to store the year (current values) before looping the days using the $_ (current month).

This looks like so.

$y | ForEach-Object {
         $currentYear = $_
         (new-Item -Path C:\testmonth\$_ -ItemType Directory)
         $d | ForEach-Object {(new-Item -Path C:\testmonth\$currentYear\$_ -ItemType Directory)}

}

CodePudding user response:

I would use a simple nested loop for this:

$Path   = 'C:\testmonth'
$Months = [CultureInfo]::CurrentCulture.DateTimeFormat.AbbreviatedMonthNames
for ($y = 2020; $y -lt 2025; $y  ) {
    for ($m = 0; $m -lt 12; $m  ) {
        $folder = Join-Path -Path $Path -ChildPath ('{0}\{1}' -f $y, $Months[$m])
        $null = New-Item -Path $folder -ItemType Directory -Force
    }
}
  • Related