PowerShell–Remove old log files
Have you ever had an application running on a server and was completely happy until you realized your drive space was slowly getting chewed up? You do a little investigation and realize that this application has been writing log files since creation and never does any cleanup. This may not be a huge problem as before with our 3Tb hard drives, however if this has been a system that’s been in production for a few years and forgotten about this could become an issue.
This isn’t completely limited to log files, some applications actually create files for you to use and leave them on the drive assuming (correctly in some cases) that you will deal with them. One application that does this and I support is IBM’s Tivoli Storage Manager (TSM). This is a data protection/backup/archive/management software and it creates disaster recovery plans on a daily basis, when configured properly. These plans get created and place in a per-determined location for you to do what you need to get them offsite so you can recover your systems and data in the event of a disaster.
I recently went into a customer’s location and they have had this system running for many years. This server was sitting in the rack just happy as could be, however they had data on the drives that went back… a long time… Unfortunately this was their history files and the disaster recovery plans from forever ago. They didn’t need to keep it beyond its useful life, which in this case is really only a few days. This is one of the scripts I wrote for them using PowerShell to clean out all the log files and DRM plans that are no longer needed.
This gets put in a file “C:\Scripts\RemoveExpiredLogs.ps1” that is scheduled to run daily.
# Author: Thomas Wimprine
# Creation Date: Dec 14, 2011
# FileName: RemoveExpiredLogs.ps1
# Description: Delete logfiles from a specified directory based on age
$RetainDays = 10 # Number of days you want to keep logs
$LogDirectory = "D:\LogDir\" # In this instance I need the trailing slash
$DeleteDate = [DateTime]::Today.AddDays(-$RetainDays)
foreach ($file in Get-ChildItem $LogDirectory) {
if ($file.CreationTime -lt $DeleteDate) {
Remove-Item $LogDirectory$file
}
}
Simple & Effective – I find myself re-writing this more often than I thought I would so I hope you enjoy…