PowerShell Script for Audit Log Cleanup
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.
### Step 1: Define the Parameters
First, we will define the number of days to keep the logs. Any logs older than this threshold will be removed.
$daysToKeep = 30 $thresholdDate = (Get-Date).AddDays(-$daysToKeep)
### Step 2: Get the Event Logs
Next, we will retrieve the security event logs. This is where logon attempts and other security-related events are stored.
$eventLogs = Get-WinEvent -LogName Security
### Step 3: Filter Old Logs
Now, we will filter the event logs to find entries that are older than the specified threshold. This will allow us to identify which logs are eligible for deletion.
$oldLogs = $eventLogs | Where-Object { $_.TimeCreated -lt $thresholdDate }
### Step 4: Remove Old Logs
Finally, we will remove the filtered old logs. Its important to proceed with caution here, as this operation is irreversible.
foreach ($log in $oldLogs) { Remove-WinEvent -LogName Security -Id $log.Id Write-Host "Removed log: $($log.Id) - Time: $($log.TimeCreated)" }
### Conclusion
This PowerShell script provides an efficient way to maintain your Security event logs by removing entries that are no longer relevant. Regularly cleaning up old logs can help with system performance and security management. Adjust the `$daysToKeep` parameter as needed based on your organization’s policies.