← script library

PowerShell Script for Audit Log Cleanup

Security & AuditingJanuary 12, 2025

In this post, we will create a PowerShell script designed to help maintain the security posture of a Windows system by cleaning up old audit logs. This script will remove logs that are older than a specified number of days, helping to manage log storage and ensure that only relevant logs are kept.

powershell
$daysToKeep = 30
$thresholdDate = (Get-Date).AddDays(-$daysToKeep)

$eventLogs = Get-WinEvent -LogName Security

$oldLogs = $eventLogs | Where-Object { $_.TimeCreated -lt $thresholdDate }

foreach ($log in $oldLogs) {
    Remove-WinEvent -LogName Security -Id $log.Id
    Write-Host "Removed log: $($log.Id) - Time: $($log.TimeCreated)"
}

Run it across your fleet

This script runs as-is on a single host. Paste it into ServerEngine to schedule it, run it on a whole server group in parallel, and keep the credentials out of the file — see the scripts documentation and the credential store.

Ready when you are.

Try ServerEngine free for 7 days.