Home > Mobile >  Archive files older than 6 months
Archive files older than 6 months

Time:12-28

Folder X has a lot of subfolders A,B,C,D... each subfolder has a lot of files and I want to archive all files that are in those subfolders and that are older than 6 months. After that check if archive is created and delete the files that have been archived.

Here is what I tried:

#$SourceFolder = "C:\Users\sec\Desktop\X"

ForEach-Object 
{
    Get-ChildItem -Path "$($_.FullName)" -Exclude "*.zip"
    Where-Object {($_.LastWriteTime -lt (Get-Date).AddMonths(-6))} |
        Compress-Archive -DestinationPath "$($_.FullName)\06.2020andOlder.zip" -Update;

    if (Test-Path 06.2020andOlder.zip) {
        Remove-Item -Force
    }
}

CodePudding user response:

Assuming you want each subfolder to end up with a .zip archive where the older files are in, try this:

Use Group-Object to group all older files within the same subdirectory together and use that to the create the .zip file and also to remove the original files after zipping.

$SourceFolder = 'D:\Test'
$refDate      = (Get-Date).AddMonths(-6).Date  # take this from midnight

Get-ChildItem -Path $SourceFolder -File -Recurse -Exclude "*.zip" | 
    Where-Object { $_.LastWriteTime -lt $refDate } |
    Group-Object DirectoryName | ForEach-Object {
        # construct the target folder path for the zip file using the Name of each group
        $zip = Join-Path -Path $_.Name -ChildPath '06.2020andOlder.zip'
        # archive all files in the group
        Compress-Archive -Path $_.Group.FullName -DestinationPath $zip -Update

        # here is where you can delete the original files after zipping
        $_.Group | Remove-Item -WhatIf
    }

Note I have added switch -WhatIf to the Remove-Item cmdlet. This is a safety switch, so you are not actually deleting anything yet. The cmdlet now only displays what would be deleted. Once you are happy with this output, remove that -WhatIf switch so the files are deleted.

  • Related