Automatically Delete Old Log Files with a Powershell Script

Clean Up Old Log Files Using a Scheduled PowerShell Script

Clean Up Old Log Files Using a Scheduled PowerShell Script

I use a scheduled task to run a script very similar to this one every midnight to clean up log files on one of my servers.

It deletes any files in c:\logs that are more than 30 days old and any files in c:\special\logs that are more than 7 days old.

Just change the paths and retention times to suite your requirements.

# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# Filename : Clean_AlpLogs.ps1
# Purpose : Deletes all files under C:\Logs and 
#         : C:\Special\Logs older than the specified number of days.

# Days to keep c:\logs files.
$LogsRetention = 30
# Days to keep C:\Special\Logs files.
$SpecialLogsRetention = 7

# Make the retention times negative.
$LogsRetention = $LogsRetention * -1
$SpecialLogsRetention = $SpecialLogsRetention * -1

# Delete the old Logs files.
$Logs = (Get-ChildItem C:\Logs | `
    ?{$_.LastWriteTime -lt (Get-Date).AddDays($LogsRetention)})
$Logs | Remove-Item

# Delete the old Special\Logs files.
$SpecialLogs = (Get-ChildItem C:\Special\Logs | `
    ?{$_.LastWriteTime -lt (Get-Date).AddDays($SpecialLogsRetention)})
$SpecialLogs | Remove-Item

Leave a Reply

Your email address will not be published.