How to group files by year and months (20200819) and archive at one location using PowerShell script

Viewed 18

I have thousands of files of many years and I want to archive these files on year -> month basis. I want to keep latest 2 months of files and older than 2 months should be archived. The catch is to determine the year and month of a specific file I have to do it from the file name.

Filename format : ABCXYZ_20220715.xml

First 4 digits are year (2022), followed by 2 digits of month(07) and 2 digits of day(15).

These files not necessarily were created on the same date as given in the file name. Otherwise it would have been easy for me to achieve this using group by $_.LastWriteTime

Below is the desired output: Desired output

Script I wrote to achieve this, but using $_.LastWriteTime and NOT from the file name.

    # Two months from the beginning of the month
$today = [datetime]::Today
$maxAge = $today.addMonths(-2)

$SourceFolder = "C:\Temp\sent"
$DestinationFolder = "C:\Temp\Archive"

$filesByMonth = Get-ChildItem -Path $SourceFolder -File |`
    where LastWriteTime -LT $maxAge |`
    group { $_.LastWriteTime.ToString("yyyy\\MM") }

foreach ($monthlyGroup in $filesByMonth) {
     $archiveFolder = Join-Path $DestinationFolder $monthlyGroup.Name
     New-Item -Path $archiveFolder -ItemType Directory -Force


          $monthlyGroup.Group | Move-Item -Destination $archiveFolder
         # $monthlyGroup.Group | Move-Item -Destination $_.fullName.Replace($SourceFolder, $archiveFolder)
        #the second $archivefolder is the name for the ZIP file, the extensions is added automatically
       
        Compress-Archive -Path $archiveFolder -DestinationPath $archiveFolder
         Remove-Item $archiveFolder -Recurse

}
0 Answers
Related