Friday, February 6, 2015

PowerShell script to purge log files older than x days

I've run into many situations where I have run low on disk space due to log files that are in desperate need of purging. Sometimes it is IIS, but I find it applies to a wide array of programs and I have searched high and low for a good option that doesn't cost anything. I wanted to share what I've come up with that has been working well for me. Since I'm in PowerShell on a daily basis running other commands, I created a LogCleaner.Ps1 script that goes to various servers and purges log files. Since some have log files I need to keep longer, I have a separate line for each server and I just add a line as I run into a new server with some new files that need to be purged.  This one hits an IIS server, SolarWinds Orion Server, a Generic Server, and a SharePoint server.

$now = get-date
get-childitem "\\server1.domain.com\c$\inetpub\logs\logfiles" -recurse| where {$_.LastWriteTime -le $now.AddDays(-7)} | del -Confirm:$false
get-childitem "\\server2.domain.com\c$\ProgramData\Solarwinds\Collector\StreamedResults\SolarWinds.Node.Wireless.Snmp" -recurse| where {$_.LastWriteTime -le $now.AddDays(-2)} | del -Confirm:$false
get-childitem "\\server3.domain.com\c$\Users\username\AppData\Local\Temp" -recurse| where {$_.LastWriteTime -le $now.AddDays(-1)} | del -Confirm:$false
get-childitem "\\server4.domain.com\c$\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\LOGS" -recurse| where {$_.LastWriteTime -le $now.AddDays(-1)} | del -Confirm:$false

You could, of course, schedule this to run and place the script on each server, if you wanted. I like just kicking it off from my workstation so I can see any errors and have the warm fuzzy feeling that it has been run without checking every server.  Since I run this on a daily basis, it never takes more than a minute to run against the 30 servers I have it configured for at this time.