Search code examples
windowsvbscriptftpevent-viewer

Extracting error logs from Windows event viewer


I want to create VBScript code to retrieve specifically error type logs from Windows Event Viewer, save them in a .txt file, and transfer it via FTP or just direct copy.

How can I achieve this?

I've been doing some reading and stumbled upon these pages:

Main question, Eventquery.vbs info and Copy file to remote computer.

But I just don't understand how to do this process as a whole.


Solution

  • You can query the Event Log using a WMI query. Here is information about the specific class.

    Without knowing exactly what you're looking for, let's assume you wanted to search the Application event logs and record any event id 1003. I use On Error Resume Next as a quick fix so it doesn't error out if a field doesn't contain data.

    On Error Resume Next
    LOG_FILE = "temp.txt"
    
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    Set colItems = objWMIService.ExecQuery("Select * from Win32_NTLogEvent WHERE LogFile='Application'")
    
    For Each objEvent in colItems
        If objEvent.EventCode = 1003 Then       
            writeLog "Category: " & objEvent.Category
            writeLog "Category String: " & objEvent.CategoryString
            writeLog "Computer Name: " & objEvent.ComputerName
            writeLog "Data: " & objEvent.Data
            writeLog "Event Code: " & objEvent.EventCode
            writeLog "Event Identifier: " & objEvent.EventIdentifier
            writeLog "Insertion Strings: " & objEvent.InsertionStrings
            writeLog "Logfile: " & objEvent.Logfile
            writeLog "Message: " & objEvent.Message
            writeLog "Record Number: " & objEvent.RecordNumber
            writeLog "Source Name: " & objEvent.SourceName
            writeLog "Time Generated: " & objEvent.TimeGenerated
            writeLog "Time Written: " & objEvent.TimeWritten
            writeLog "Type: " & objEvent.Type
            writeLog "User: " & objEvent.User 
            writeLog ""  
        End If
    Next
    
    Sub writeLog(strText)
      Dim objFSO, objLogFile
      
      Set objFSO = CreateObject("Scripting.FileSystemObject")  
      Set objLogFile = objFSO.OpenTextFile(LOG_FILE, 8, True)
    
      objLogFile.WriteLine strText
      objLogFile.Close
      
      Set objLogFile = Nothing
      Set objFSO = Nothing
    
    End Sub