Objective
Prevent a Windows server from filling its disk when event-log archiving is enabled by deleting only archived EVTX files older than an approved retention period, without clearing active logs or bypassing evidence-retention requirements.
Prerequisites
- The actual path where Windows stores archived EVTX files.
- An approved retention period such as 30, 60, 90, or 180 days.
- SYSTEM or a service account with read/delete rights on the archive directory.
- A protected log directory where the cleanup script can record its actions.
- Enough free disk space to test safely rather than making changes under an immediate capacity emergency.
Step-by-step procedure
Check the active log configuration
Read the configuration of the event log that archives when full. Confirm the active file path, maximum size, and retention behavior so the cleanup targets Windows-generated archives rather than a live log moved to a custom location. Preserve the output before making changes.
wevtutil gl SecurityGet-WinEvent -ListLog Security | Select LogName,FileSize,MaximumSizeInBytes,LogMode,LogFilePath- The active log path and archival mode are documented.
List archives without deleting anything
List Archive-*.evtx files with their timestamps, sizes, and full paths. Do not add deletion yet. Verify that the pattern cannot match Security.evtx, System.evtx, Application.evtx, or another active log.
Get-ChildItem 'C:WindowsSystem32winevtLogs' -Filter 'Archive-*.evtx' -File | Sort LastWriteTime | Select FullName,LastWriteTime,Length- The candidate list contains archived files only and no active event log.
Define retention and estimate the impact
Choose a retention period that matches policy, then calculate how many files and bytes would be removed. Treat this as the dry run. If the result is unexpectedly large, stop and recheck the path, filename pattern, and date field before enabling deletion.
$RetentionDays = 90$Cutoff = (Get-Date).AddDays(-$RetentionDays)$Candidates = Get-ChildItem 'C:WindowsSystem32winevtLogs' -Filter 'Archive-*.evtx' -File | Where-Object LastWriteTime -lt $Cutoff$Candidates | Measure-Object Length -Sum$Candidates | Select FullName,LastWriteTime,Length- The number and total size of candidate archives are approved before deletion.
Create a PowerShell script with safeguards
Store the script in an administrator-controlled directory and parameterize the archive path, retention, and action log. The script should select only Archive-*.evtx files older than the cutoff, log each action, and stop safely if the target path does not exist. Avoid broad patterns such as *.evtx.
New-Item -ItemType Directory -Path 'C:Scripts' -Force- The script is stored in a protected location and targets archived logs only.
Test the script without Remove-Item
Run an inventory-only version that writes the candidate list to a file or console. Compare several files with Event Viewer and, if a SIEM is used, verify that at least one older event is already available in the collector before local deletion.
$Candidates | ForEach-Object { "WOULD DELETE $($_.FullName) $($_.LastWriteTime)" } | Out-File 'C:ScriptsArchiveLogPurge-test.log' -Append- The dry run matches exactly the archives that policy allows you to remove.
Enable deletion with logging
After validating the dry run, use Remove-Item -LiteralPath so special characters are not interpreted unexpectedly. Log each deletion and capture errors. The script should continue safely when one file is locked while clearly reporting the failure.
$Candidates | ForEach-Object { try { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction Stop; "DELETED $($_.FullName)" | Out-File 'C:ScriptsArchiveLogPurge.log' -Append } catch { "ERROR $($_.FullName) $($_.Exception.Message)" | Out-File 'C:ScriptsArchiveLogPurge.log' -Append } }- Archives older than the retention period are deleted and every action is traceable.
Create the scheduled task under SYSTEM
Create a daily task during a low-load period. Running under SYSTEM avoids storing a user password and normally provides the required local rights. Launch PowerShell with -NoProfile, an execution policy compatible with your organization, and the explicit script path.
$Action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument '-NoProfile -File "C:ScriptsPurge-ArchivedEventLogs.ps1"'$Trigger = New-ScheduledTaskTrigger -Daily -At 3:15am$Principal = New-ScheduledTaskPrincipal -UserId 'SYSTEM' -LogonType ServiceAccount -RunLevel HighestRegister-ScheduledTask -TaskName 'BOAI - Purge archives journaux' -Action $Action -Trigger $Trigger -Principal $Principal -Description 'Supprime les Archive-*.evtx plus anciens que la retention validated'- The task exists, runs under SYSTEM, and stores no user password.
Run the task manually and verify the result
Trigger the task once, then check LastTaskResult and the script log. Measure free space before and after the run and verify that active event logs still receive new events without EventLog service errors.
Start-ScheduledTask -TaskName 'BOAI - Purge archives journaux'Start-Sleep -Seconds 10Get-ScheduledTaskInfo -TaskName 'BOAI - Purge archives journaux'Get-Volume -DriveLetter C | Select SizeRemaining- The task completes successfully and active event logging remains healthy.
Monitor the task and disk capacity
Alert on scheduled-task failures and low disk space. Cleanup should not hide an abnormal surge in event volume, so investigate if archives grow much faster than normal. Revisit retention whenever compliance requirements change.
- Cleanup prevents disk saturation without hiding abnormal event growth or silently shortening retention.
Validation
The procedure is validated when:
- Active Security, System, and Application logs are never deleted or cleared.
- Only Archive-*.evtx files older than the approved retention period are removed.
- The scheduled task runs under SYSTEM with the expected LastTaskResult.
- Disk usage stabilizes and each deletion is logged.
Rollback
- Disable or remove the scheduled task if the path, pattern, or retention is wrong.
- Restore archived EVTX files from backup if they were deleted but should have been retained.
- Return the script to dry-run mode until a revised policy is validated.
- Do not fabricate a deleted EVTX file; recover it from backup or the SIEM when available.
Troubleshooting / common errors
- If no files are selected, verify the archive path, filename pattern, and LastWriteTime cutoff.
- If files cannot be deleted, check ownership, SYSTEM permissions, locks, and the script log.
- If disk usage still grows, investigate event-generation volume instead of shortening retention automatically.