Archiving Event Logs

By |2017-12-01T11:41:34+00:00June 3rd, 2010|PowerShell|0 Comments

As part of a recent engagement I was asked to implement a solution to automatically export & archive System and Security logs from servers to a central location, the requirements were:

  • Nightly time stamped archive of Security and System event logs to a central location
  • Clear the local log once the archive has been successfully taken

I put together the following PowerShell script to achieve the above:


$locallocation = "c:logs"
$remotelocation = "fileserverEventLogs"
$localmachine = $env:computername

$evtlgs = Get-WMIObject -Class Win32_NTEventLogFile -Computer $localmachine
foreach ($log in $evtlgs)
    if ($log.LogFileName -eq "System" -or $log.LogFileName -eq "Security")
        $timestamp = get-date -f yyyyMMddHHmmss
        $path = $log.LogFileName + $timestamp
        $store = $locallocation+$path+".evt"
        $backup = ($log.backupeventlog($store)).ReturnValue
        if($backup -eq 0)
            $log.ClearEventLog() | out-null
        move-item $locallocation* $remotelocation$localmachine

The above script is executed by a Scheduled Task (which on another note are brilliant on Server 2008), the lines you’re interested in are the top 2 lines which configure a local location to write the log out to and the remote location to move the log to once it has been written.  I ran this script using a service account which has permission to write to the local and remote locations. 

If you wanted a different selection of logs to be archived you would adjust the

if ($log.LogFileName -eq "System" -or $log.LogFileName -eq "Security")

line to suit your requirements.

In our requirement the logs had to be archived daily, this was simply achieved by configuring task scheduler to run once per day at the desired time, no code changes are required. 

The requirement for only clearing the local log if the export was successful is met by checking the exit code form the backup, if this wasn’t 0 then the log wont be cleared.

Leave A Comment

like what you see? 

Sign-up to our newsletter and never miss out on the latest blogs, events and tech news from the world of risual
Give it a try, you can unsubscribe anytime.