How to compress/zip files older than x days and delete the original files post compression using power shell script.


If your application is generating huge log files everyday or you have a big database backup which needs to be stored somewhere then definitely storage space is one of the big concerns here. By compressing the files you can save a lot of storage space. But compressing files manually on a daily basis is one tedious job!

Here’s a solution by power shell script which will compress the files older than x days and delete the original files post verifying the creation of compressed zip file.

Prerequisites:-

  • Install 7zip tool on your windows machine through this link – https://www.7-zip.org/download.html
    NOTE:- 7-Zip is a free and open-source file archiver for compressing and uncompressing files. You can also use Compress-Archive cmdlet, But the maximum file size is 2 GB because there’s a limitation of the underlying API.
  • Mention the number of days before which the files have to be compressed in the LastWrite variable.
  • Change the folder path of the files and Filter(type of the file) as per your need.
  • Save the below power shell script with .ps1 extension and run it. post script execution you should be able to see compressed files with the name of the original file and the date of compression.
  • You can schedule this script to run on a daily basis using Windows Task Scheduler.

Power Shell script:-

## Adding 7zip to environment variables.
$7zippath = “$env:ProgramFiles\7-Zip\7z.exe”
Set-Alias 7zip $7zippath

## Replace x with the number of days before which the files have to be compressed.
$LastWrite = (get-date).AddDays(-x)
$date=(Get-Date).ToString(‘yyyyMMdd’)

## Replace Path and Filter as per your need.
$Files = Get-ChildItem -Path “D:\Logs_folder” -Filter “*.txt” -Recurse -File | Where-Object {$_.LastWriteTime -le $LastWrite}

ForEach ($File in $Files) {
“Compressing Log $File”
7zip a “$($File.fullname)$date.zip” “D:\Logs_folder\$File

if((Test-Path “$($File.fullname)$date.zip”))
{
“Log Compression succeeded, so deleting D:\Logs_folder\$File”
Remove-Item -Path “D:\Logs_folder\$File”
}
else
{
“Log Compression FAILED, Please check parameters are passed correctly”
}
}

Leave A Comment

Your email address will not be published. Required fields are marked *