Powershell function for rotating event logs

A friend of mine came to me with an interesting powershell challenge today: how can I use powershell to archive and clear event logs?

Well, challenge accepted!

The reason the challenge arose is due to maintenance he performs on a number of customer servers. Every month he saves each eventlog and clears it manually, a time consuming task if you have more than a few servers.

So here’s what I came up with:
A powershell function, Rotate-EventLogs, that exports the application, system and security logs to xml files with todays date as filename, then the logs are cleared.

The function isn’t really all that advanced, it checks if the folders where the logs will be saved exists, if not it will create them.
Then it will export each log to c:eventlogs<logname>%d%m%Y.xml For example the system log exported today would be located at c:eventlogssystem6092012.xml.
After the export of the three eventlogs it will clear them.

What he will have to do manually is to add the function code to %windir%system32WindowsPowerShellv1.0profile.ps1 on each server.

He can then set up a scheduled task that only runs Rotate-Eventlogs in a powershell window every month.

Challenge completed!

Here’s the code for the function:

function Rotate-EventLogs
{
$today = get-date -UFormat %d%m%Y
 
if ((Test-Path c:eventlogs) -eq $False)
{
New-Item c:eventlogs -type directory
}
 
if ((Test-Path c:eventlogssystem) -eq $False)
{
New-Item c:eventlogssystem -type directory
}
 
if ((Test-Path c:eventlogsapplication) -eq $False)
{
New-Item c:eventlogsapplication -type directory
}
 
if ((Test-Path c:eventlogssecurity) -eq $False)
{
New-Item c:eventlogssecurity -type directory
}
 
Get-EventLog system | export-clixml c:eventlogssystem$today.xml
Get-EventLog application | export-clixml c:eventlogsapplication$today.xml
Get-EventLog security | export-clixml c:eventlogssecurity$today.xml
 
Clear-EventLog system,application,security
 
}

Have fun with it if you want. If not, don’t :)

UPDATE: If you want to do this remotely you can take a look at this file: https://dl.dropbox.com/u/33041052/bloggting/scriptstuff/powershell/function/rotate-eventlogs_espen_style.ps1
It adds the capability to do it on a remote server, see the help section of the function

Leave a Reply

Your email address will not be published. Required fields are marked *