Compress Logs Older Than 30 Days With 7-Zip
Managing server storage requires automating the cleanup and archiving
of growing log files. This guide demonstrates how to write an automated
PowerShell script that identifies .log files older than 30
days, compresses each file into a high-ratio archive using the 7-Zip
command-line utility, and safely removes the original uncompressed files
to reclaim storage space.
Prerequisites
Before running the script, ensure the following requirements are met:
- 7-Zip is installed (the standard path is typically
C:\Program Files\7-Zip\7z.exe). - You have read, write, and execute permissions in the target log folder.
- PowerShell is available on the system.
The PowerShell Automation Script
Save the following code as a .ps1 file, such as
Compress-OldLogs.ps1:
# Configuration
$LogFolder = "C:\Path\To\Your\Logs"
$SevenZipExe = "C:\Program Files\7-Zip\7z.exe"
$DaysOld = 30
$Extension = "*.log"
# Verify 7-Zip installation
if (-not (Test-Path -Path $SevenZipExe)) {
Write-Error "7-Zip executable not found at $SevenZipExe"
exit 1
}
# Calculate threshold date
$CutoffDate = (Get-Date).AddDays(-$DaysOld)
# Retrieve and process target files
Get-ChildItem -Path $LogFolder -Filter $Extension -File | Where-Object {
$_.LastWriteTime -lt $CutoffDate
} | ForEach-Object {
$ArchiveFile = "$($_.FullName).7z"
# Run 7-Zip compression with delete-on-success flag (-sdel)
& $SevenZipExe a -t7z -mx=7 -sdel "$ArchiveFile" "$($_.FullName)"
if ($LASTEXITCODE -eq 0) {
Write-Output "Successfully compressed: $($_.Name)"
} else {
Write-Warning "Failed to compress: $($_.Name)"
}
}Script Breakdown and Command Parameters
Get-ChildItemandWhere-Object: Recursively or directly locates files matching the$Extensionpattern where theLastWriteTimeattribute is earlier than the calculated cutoff date ((Get-Date).AddDays(-30)).a: The 7-Zip command to create or add files to an archive.-t7z: Sets the archive format to.7z, which provides superior compression ratios compared to standard.zip.-mx=7: Specifies the compression level on a scale from 0 to 9. Level 7 (Maximum) provides strong compression without excessive CPU overhead.-sdel: Instructs 7-Zip to delete the source file only after the archive is successfully generated, preventing duplicate copies and ensuring failed compressions do not delete data.
Scheduling the Script
To run the script automatically without manual intervention, configure Windows Task Scheduler:
- Open Task Scheduler and select Create Basic Task.
- Set your preferred trigger (e.g., Daily or Weekly).
- Under the Action step, choose Start a program.
- In the Program/script field, enter:
powershell.exe - In the Add arguments field, enter:
-ExecutionPolicy Bypass -File "C:\Scripts\Compress-OldLogs.ps1" - Finish the setup, ensuring the task is set to run whether the user is logged on or not with highest privileges.