O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Windows Server Hacks
By Mitch Tulloch
March 2004
More Info

HACK
#96
Back Up and Clear the Event Logs
Here's a nifty script you can use to back up and clear the Event logs on your servers
The Code
[Discuss (0) | Link to this hack]

The Code

Type the following script into Notepad (make sure to have Word Wrap disabled), and save it with a .vbs extension as archivelogs.vbs:

Option Explicit
On Error Resume Next
Dim numThreshold
Dim strMachine
Dim strArchivePath
Dim strMoniker
Dim refWMI
Dim colEventLogs
Dim refEventLog

If WScript.Arguments.Count < 2 Then
WScript.Echo _
"Usage: archivelogs.vbs <machine> <archive_path> [threshold]"
WScript.Quit
End If

If WScript.Arguments.Count = 2 Then
numThreshold = 0
Else
numThreshold = WScript.Arguments(2)
If Not IsNumeric(numThreshold) Then
WScript.Echo "The third parameter must be a number!"
WScript.Quit
End If

If numThreshold < 0 OR numThreshold > 100 Then
WScript.Echo "The third parameter must be in the range 0-100"
WScript.Quit
End If
End If

strMachine = WScript.Arguments(0)
strArchivePath = WScript.Arguments(1)

strMoniker = "winMgmts:{(Backup,Security)}!\\" & strMachine
Set refWMI = GetObject(strMoniker)
If Err <> 0 Then
WScript.Echo "Could not connect to the WMI service."
WScript.Quit
End If

Set colEventLogs = refWMI.InstancesOf("Win32_NTEventLogFile")
If Err <> 0 Then
WScript.Echo "Could not retrieve Event Log objects"
WScript.Quit
End If

For Each refEventLog In colEventLogs
'if shouldAct( ) returns non-zero attempt to back up
If shouldAct(refEventLog.FileSize,refEventLog.MaxFileSize) <> 0 Then
If refEventLog.ClearEventLog( _
makeFileName(refEventLog.LogfileName)) = 0 Then
WScript.Echo refEventLog.LogfileName & _
" archived successfully"
Else
WScript.Echo refEventLog.LogfileName & _
" could not be archived"
End If
Else
WScript.Echo refEventLog.LogfileName & _
" has not exceeded the backup level"
End If
Next
Set refEventLog = Nothing
Set colEventLogs = Nothing
Set refWMI = Nothing

Function shouldAct(numCurSize, numMaxSize)
If (numCurSize/numMaxSize)*100 > numThreshold Then
shouldAct = 1
Else
shouldAct = 0
End If
End Function

Function makeFileName(strLogname)
makeFileName = strArchivePath & "\" & _
strMachine & "-" & strLogname & "-" & _
Year(Now) & Month(Now) & Day(Now) & ".evt"
End Function


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.