Monday, January 6, 2014

Compress Old Files with PowerShell

The Story


The following PowerShell script will compress files that are older than the specified amount of time. It is handy for archiving IIS Logs, SQL Backups, etc.
The script uses 7-zip so you obviously have to have it installed (or the exe copied somewhere). It's using maximum compression which is resource intensive, if you don't want that just remove the "-mx9 -m0=lzma2" parameters.


The Script

$path = "C:\inetpub\logs\LogFiles\"
$mask = "*.log"

$days = 7

$files = dir $path -Recurse -Include $mask | where {($_.LastWriteTime -lt (Get-Date).AddDays(-$days).AddHours(-$hours).AddMinutes(-$mins)) -and ($_.psIsContainer -eq $false)}


ForEach ($file in $files) {

    & "C:\Program Files\7-Zip\7z.exe" u -mx9 -t7z -m0=lzma2 ($file.FullName + ".7z") $file.FullName
    if ($LASTEXITCODE -eq 0) {
        Remove-Item $file
    }

}

Resources

3 comments:

  1. How do you compress based on grouping

    Get-ChildItem C:\Users\xxx\xx -filter "*psv.*" | group {"{0:MMMM} {0:yyyy}" -f $_.LastWriteTime}

    Say I have 1 thousand files from different months, I want to put into zip files all of those from Jan, Feb, March into their individual compressed folders

    ReplyDelete