Weekly Windows Event Log Rotation and Archiving with PowerShell
Difficulty: Intermediate |
Time Required: 20-30 minutes
Windows servers and desktops can accumulate event logs quickly. A weekly rotation and archiving process helps keep log files manageable, makes long-term audits easier, and prevents disk space from filling up. This tutorial shows you how to rotate and archive key Windows event logs with a simple PowerShell script and schedule it to run weekly.
Prerequisites
- Administrative privileges on the target Windows 10/11 machine (or server equivalent).
- PowerShell 5.1 (comes with Windows 10/11) or newer. The script below uses built-in cmdlets and the wevtutil utility.
- A dedicated archive folder with sufficient disk space, e.g. C:\EventLogArchive. Ensure the folder has read/write permissions for the administrator user (and any service accounts if you plan to run as a scheduled task).
- Logs to rotate: by default, Application and System are included. Security is not rotated in this tutorial due to strict permissions on clearing that log; you can adjust after understanding your environment.
Note: Some logs/functions may be restricted by policy or require elevated privileges. Always test in a non-production environment first.
Step-by-step Instructions
1) Plan which logs to rotate
- By default, we’ll rotate Application and System logs.
- Optional: Add ForwardedEvents or other custom logs if you know your environment.
2) Prepare the archive location
- Create a folder to store the archived .evtx files.
- Example: C:\EventLogArchive
- Ensure permissions allow the script to write and delete.
3) Create the PowerShell script
- Save as C:\Scripts\ArchiveEventLogs.ps1 (adjust paths as needed).
- The script exports logs to a timestamped .evtx file, clears the source log after a successful export, and trims old archives beyond a retention window.
Code: ArchiveEventLogs.ps1
Code:
<#
.SYNOPSIS
Weekly rotation and archiving of selected Windows event logs. .DESCRIPTION
Exports selected event logs to timestamped .evtx archives, clears the source logs,
and removes archives older than a retention window. .NOTES
- Requires Administrator privileges.
- Windows 10/11 compatible.
- Security log is intentionally skipped for rotation due to permissions.
#> param( [string]$ArchiveRoot = "C:\EventLogArchive", [string[]$LogNames = @("Application", "System"), [int]$RetentionDays = 30 # how long to keep archived logs) # Ensure archive directory exists
if (-not (Test-Path -Path $ArchiveRoot) { New-Item -Path $ArchiveRoot -ItemType Directory -Force | Out-Null
} # Simple log for this run
$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
$runLog = Join-Path $ArchiveRoot "ArchiveLog-$timestamp.txt"
"Starting event log archive run at $(Get-Date)" | Out-File -FilePath $runLog -Encoding utf8 foreach ($log in $LogNames) { # Skip Security for rotation due to policy/permissions if ($log -eq "Security") { "[$timestamp] Skipping Security log (not rotating due to permissions)." | Add-Content -Path $runLog continue } $dest = Join-Path $ArchiveRoot "$log-$timestamp.evtx" try { # Export the log to an EVTX file wevtutil epl "$log" "$dest" if ($LASTEXITCODE -eq 0) { "[$timestamp] Archived '$log' to '$dest'." | Add-Content -Path $runLog # Clear the log after a successful export wevtutil cl "$log" 2>$null if ($LASTEXITCODE -eq 0) { "[$timestamp] Cleared '$log' log after archiving." | Add-Content -Path $runLog } else { "[$timestamp] WARNING: Failed to clear '$log' after archiving." | Add-Content -Path $runLog } } else { "[$timestamp] ERROR: Failed to archive '$log' (exit code $LASTEXITCODE)." | Add-Content -Path $runLog } } catch { "[$timestamp] EXCEPTION archiving '$log': $_" | Add-Content -Path $runLog }
} # Retention cleanup: remove archives older than RetentionDays
$cutoff = (Get-Date).AddDays(-$RetentionDays)
Get-ChildItem -Path $ArchiveRoot -Filter "*.evtx" | Where-Object { $_.LastWriteTime -lt $cutoff } | ForEach-Object { try { Remove-Item -Path $_.FullName -Force "[$timestamp] Removed old archive: $($_.Name)" | Add-Content -Path $runLog } catch { "[$timestamp] Failed to remove old archive: $($_.FullName) - $_" | Add-Content -Path $runLog }
} "Archive run completed at $(Get-Date)" | Add-Content -Path $runLog
Notes on the script:
- Logs exported: Application and System by default.
- Security log is skipped for safety and policy reasons; if you need to rotate it, test in a controlled environment and ensure you have proper permissions.
- RetentionDays controls how long the archived .evtx files stay in the archive folder. Adjust as needed.
- A per-run log file (ArchiveLog-<timestamp>.txt) is created in the archive folder so you can review what happened.
4) Test the script manually
- Open an elevated PowerShell session.
- Run: powershell -ExecutionPolicy Bypass -File "C:\Scripts\ArchiveEventLogs.ps1"
- Check the archive folder for new files named like Application-2025-11-06_02-00-00.evtx and System-2025-11-06_02-00-00.evtx.
- Review ArchiveLog-*.txt for details and ensure logs were cleared post-export.
5) Schedule the script to run weekly
Windows Task Scheduler is a solid choice for weekly rotation.
Option A: GUI (recommended for clarity)
- Open Task Scheduler > Create Task.
- General: Name = "Weekly Event Log Archive", Run with highest privileges, Configure for Windows 10/11.
- Trigger: New Trigger > Weekly > Recur every 1 week; Start: Sunday 02:00.
- Action: New Action > Start a program > Program/script: powershell
- Add arguments: -ExecutionPolicy Bypass -File "C:\Scripts\ArchiveEventLogs.ps1"
- Conditions/Settings: Allow task to run on battery if laptop; Stop if running longer than 1 hour (adjust as needed).
- Save and exit.
Option B: Command line (repeatable and script-friendly)
- Create a scheduled task with schtasks:
schtasks /Create /TN "WeeklyEventLogArchive" /TR "powershell -ExecutionPolicy Bypass -File C:\Scripts\ArchiveEventLogs.ps1" /SC WEEKLY /D SUN /ST 02:00 /RL HIGHEST
- Ensure the task has "Run with highest privileges" enabled if needed.
6) Validate after the first run
- Manually trigger the task or wait until Sunday 02:00.
- Confirm:
- New archive files exist in C:\EventLogArchive (e.g., Application-YYYY-MM-DD_HH-MM-SS.evtx).
- The source logs (Application, System) have been cleared.
- The run log shows a successful export and clear for each log.
7) Extend or customize (optional)
- Add more logs to the rotation by editing the $LogNames array in the script.
- Change retention: modify -RetentionDays to keep smaller or larger archives.
- Add a notification: append an email or Slack message by hooking into a mail/REST call in the script after each run.
- For enterprise use, consider a dedicated network share for archives and tighter access controls.
Tips and Troubleshooting Notes
- Run as Administrator: The script uses wevtutil, which requires elevated rights to export and clear logs. Always run the script from an elevated PowerShell session or schedule the task with highest privileges.
- Security log caveat: The Security log is highly protected. Clearing or exporting it may be restricted in some environments. If you must rotate Security, test carefully and ensure policy compliance.
- Execution policy: If you encounter ExecutionPolicy restrictions, run with -ExecutionPolicy Bypass for the scheduled task, or digitally sign the script.
- Log clearing failures: If a log cannot be cleared after export, double-check that no services or applications are actively writing to it during rotation. Be mindful of any dependent tasks that rely on a specific log state.
- Disk space: The archive folder can grow quickly. The RetentionDays setting helps, but monitor disk space and adjust as needed.
- Time consistency: If you operate across time zones, ensure the scheduled task uses the correct local time and that the timestamps in file names reflect your policy.
- Testing: Always test with non-critical logs first. Consider running a test script on a dev machine or a virtual machine before production use.
Conclusion
Weekly rotation and archiving of event logs keeps your system lean, accelerates audits, and protects historical data without sacrificing current monitoring. With a small PowerShell script and a weekly scheduled task, you gain automated, reliable log management that works out-of-the-box on Windows 10 and Windows 11.
Key benefits include:
- Predictable, time-bound log archiving to prevent disk space issues.
- Simple restoration path for incident investigations via timestamped .evtx files.
- Clear separation between current logging and long-term retention with an adjustable window.
Regularly review the archive strategy (logs included, retention period, and storage location) to keep it aligned with your organization's needs.
This tutorial was generated to help WindowsForum.com users get the most out of their Windows experience.
Key Takeaways:
- Automate weekly rotation and archiving of key event logs with a simple PowerShell script.
- Keep current logs lean while preserving historical data for audits and troubleshooting.
- Use Scheduled Tasks (or GUI) to reliably run the job on Windows 10/11; adjust retention to fit your storage constraints.