Categories
How To Powershell Tech

Backup and clear all Windows Event Logs using Powershell

Whenever I’m building a new server, PC or Windows VM, I like to clear all the event logs before turning it over to the end users. This way if any issues occur, I’m not trying to filter through thousands of useless event logs that occurred during the build process. There are a myriad of event logs to pour over now days in the Windows Event Viewer. There are your standard Windows Logs, App, Security, Setup, System:

Then there are the Applications and Services Logs:

There are the Microsoft Logs, Hardware Event logs and it goes on. If you want to quickly backup and clear all the logs, unfortunately the event log GUI doesn’t give you an easy way to do this. I wrote this Powershell script to accomplish this task in one fell swoop.  

$LOGS = wevtutil el
$PATH = Test-path C:\backup
if ($PATH -eq $false)
{
    New-Item -Path c:\backup -ItemType directory
}

Foreach($LOG in $LOGS)
{
           
    wevtutil epl $log c:\backup\$log.evtx
    
    wevtutil cl $log     
    
} 

The script will create a backup folder on the C:\ drive if it doesn’t exist (change this path to suit your needs). It will then enumerate all the Event Logs, back each one up to the backup folder and then clear it before moving on to the next log.

Before:

After running script:

The events that are 68KB are the empty ones.

There are a few caveats to running this. One, you will see errors when you run this script, it will try to enumerate logs that don’t exist. Because wevtutil is not a native Powershell command, there is no error suppression available. And Try{} Catch{} won’t work either. Just ignore the errors. Another thing to keep in mind, it will backup logs whether they have data or not. You could probably add some query logic to only backup logs that have data, but you’re probably never going to use these logs anyway. At least you can tell your boss you backed them all up before you deleted them.