log rotate and archive with windows

I support a few applications which run on windows and there isn’t really any great way of rotating the logs like there is with linux. While the logs are all configured to go to off host log solutions such as Azure logs or elasticsearch I like to keep the local logs around for a period of time as well. Depending on your rules some fidelity or information may be lost when the logs are ingested into these solutions. I have tried using some of the built-in compression functionality with windows but some of the log files are so large they generate out of memory errors. I have found 7zip to be the best tool for these large files. The compression rate and performance is better.

One such application where I want to compress all logs older than 7 days and then keep for 90 days is bitvise.

You must install 7zip on the computer first, but then you can run the script below on demand or on a schedule. e.g. every night or weekend.

#Get all log files older than 7 days and compress to archive then delete source
cd “C:\Program Files\Bitvise SSH Server\Logs”
foreach ($file in Get-ChildItem -Filter *.log -Path “C:\Program Files\Bitvise SSH Server\Logs” | Where-Object { $_.LastWriteTime -lt (get-date).AddDays(-7)})
{
& “C:\Program Files\7-Zip\7z.exe” -sdel -mx=5 a “$file`.7z” “$file”
}

#Get all old 7zip archives and delete when older than 90 days
Get-ChildItem -Filter *.7z -Path “C:\Program Files\Bitvise SSH Server\Logs” | Where-Object { $_.LastWriteTime -lt (get-date).AddDays(-90)} | Remove-Item -Force -Verbose