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
- http://stackoverflow.com/questions/16613656/how-can-i-check-if-a-file-is-older-than-a-certain-time-with-powershell
- http://stackoverflow.com/questions/1673967/how-to-run-exe-in-powershell-with-parameters-with-spaces-and-quotes
- http://blogs.msdn.com/b/daiken/archive/2007/02/12/compress-files-with-windows-powershell-then-package-a-windows-vista-sidebar-gadget.aspx
- http://stackoverflow.com/questions/2081795/invoke-an-exe-from-powershell-and-get-feedback-on-succes-or-failure
Nice and simple. Thanks!
ReplyDeleteHow do you compress based on grouping
ReplyDeleteGet-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
Works well.
ReplyDelete