Guy’s Scripting Ezine 39 – WMI and Event Logs

Contents for Guy’s Scripting Ezine 39 WMI and Event Logs

 ♣

This Week’s Secret

This is my dilemma when writing scripts, on the one hand I want to build a script which is valuable, but on the other hand, I do not want to fall into the trap of making the code so long and so complicated that you cannot trace its logic.  My benchmark for a script is this, can you amend the script to suit your network and your interests? To help you get the most from my scripts I am adding more and more comments as well as providing Learning Points at the end of each example.

A classic network Manager’s job – Checking the Event Logs

As a top network manager you need to know if there is anything suspicious in the event log.  Could there have been a security breach, was someone trying to hacking in?  Worse, were they successful?  Alternatively, it may be a more mundane problem, perhaps that old ServerOne is running out of disk space – again.  Remember that being in charge, you have 3 choices, delegate, script it your self or buy a tool.

WMI and Event Logs

WMI – Windows Management Interface.

For a script writer, WMI is like a door to enter an Aladdin’s cave of server tools.  Now to begin with, it seems as though you have to be a magician to make the tools work.  But rest assured, I will guide you through the WMI methods and syntax. 

This week’s VBScript uses WMI to extract information from the operating system.  This week I will help you create scripts which retrieve information from the event logs.  As usual, my goal is to get you started.  However, along the journey I will show you VBScripting methods like: GetObject("winmgmts:" …) and .writeline, which you can apply to other projects.

Guy Recommends: WMI Monitor and It’s Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft’s operating systems.  Fortunately, SolarWinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your scripts.

Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server. Give this WMI monitor a try – it’s free.

Download your free copy of WMI Monitor

Example Script to Interrogate the System Log

Scenario:

You want to extract a particular event ID from the system log.  Let us pretend that you have become paranoid about synchronizing the time on all servers.  Following a little research of the system log, you want a list of all records showing WinTime Event ID:12. 

Talking of dilemma’s.  I was torn between putting in an extra message box to show that something was happening, and just leaving you to wait for an eternity before your first file is created.  In the event I put in two message boxes.  Warning, remember that you must dismiss the FIRST message box so that the script will continue processing.  Suggestion, once you realise how long the script needs to process the logs, then ‘ Rem out the WScript.Echo " Press OK.."

Instructions

  1. Pre-requisites.  For this script to work, you need any modern operating system Windows 2000, 2003 or XP.
  2. Copy and paste the script below into notepad. Important: Check the Variables section of the script, make alterations to strFolder.
  3. Save the file with .vbs extension e.g. Event12.vbs.
  4. Double click.  Press OK to dismiss the first Message Box.  I hope you didn’t get a ‘Path not found error’ if you did check 3.
  5. WARNING, Note well, nothing more will happen until you dismiss the First Message box.
  6. Use the second the message box to find your text file!

‘ EventID12.vbs
‘ Example VBScript to check the Event ID.
‘ Version 1.9
‘ Guy Thomas 1st August 2004

Option Explicit

Dim objFso, objFolder, objWMI, objEvent ‘ Objects
Dim strFile, strComputer, strFolder, strFileName, strPath ‘ Strings
Dim intEvent, intNumberID, intRecordNum, colLoggedEvents

‘ ——————————————–
‘ Set your variables
intNumberID = 12 ‘ Event ID Number
intEvent = 1
intRecordNum = 1

strComputer = "."
strFileName = "\Event12.txt"
strFolder = "C:\GuyScripts"
strPath = strFolder & strFileName

‘ —————————————-
‘ Section to create folder to hold file.
Set objFso = CreateObject("Scripting.FileSystemObject")

If objFSO.FolderExists(strFolder) Then
    Set objFolder = objFSO.GetFolder(strFolder)
Else
   Set objFolder = objFSO.CreateFolder(strFolder)
   Wscript.Echo "Folder created " & strFolder
End If
Set strFile = objFso.CreateTextFile(strPath, True)

‘——————————————–
‘ Next section creates the file to store Events
‘ Then creates WMI connector to the Logs

Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = ‘System’" )

Wscript.Echo " Press OK and Wait 30 seconds (ish)"
‘ —————————————–
‘ Next section loops through ID properties
intEvent = 1
For Each objEvent in colLoggedEvents
If objEvent.EventCode = intNumberID Then

strFile.WriteLine ("Record No: ")& intEvent
‘ strFile.WriteLine ("Category: " & objEvent.Category)
strFile.WriteLine ("Computer Name: " & objEvent.ComputerName)
strFile.WriteLine ("Event Code: " & objEvent.EventCode)
‘ strFile.WriteLine ("Message: " & objEvent.Message)
‘ strFile.WriteLine ("Record Number: " & objEvent.RecordNumber)
strFile.WriteLine ("Source Name: " & objEvent.SourceName)
‘ strFile.WriteLine ("Time Written: " & objEvent.TimeWritten)
strFile.WriteLine ("Event Type: " & objEvent.Type)
strFile.WriteLine ("User: " & objEvent.User)
strFile.WriteLine (" ")
intRecordNum = intRecordNum +1
End if
IntEvent = intEvent +1
Next
Wscript.Echo "Check " & strPath & " for " &intRecordNum & " events"

WScript.Quit

‘ End of Guy’s example VBScript

Learning Points

Note 1:  ‘ Top Section

Here are ‘ Remarks.  Just for our reference.

Option Explicit – This forces me to declare my variables, which I do with Dim (dimension) statements.  Guy loosely follows the Hungarian convention where the ‘str’ prefix means a string variable where as ‘int’ means an integer or number.  Guess what obj means?  Yes object.

Note 2: ‘ Set your variables

If Guy wrote the script, then always check the script for variables.  Whilst I try to design scripts which run as automatically as possible, there are occasions – such as this script, where you need to adjust a variable.  It would be boring if I set the path to C:\, so change strPath to match a file in a folder on your machine.  In the case of this script, I hope that editing strPath will make you think, ‘Where should I look for the output?’

The variables beginning with ‘int’ are for numbers.

Note 3: FSO – Primer.

How can we output the information?  WScript.Echo has its place, but in this example it would swamp you with data and give you RSI from clicking the message boxes.  No, we need a different vehicle for the output.  This is where FSO comes in handy, use objFSO to create a file object corresponding to strFile.  We can then fill strFile with data from the event logs.  The idea is that we use notepad to read the events at our leisure.  As a matter of interest, ‘True’ in this context means over-write the file referenced by strPath.

Time to take a break from our long journey to find those events log IDs.  Please find the time to admire how the script creates the c:\GuyScripts folder. Once again, check how FSO uses those ‘Get’ and ‘Create’ statements, as in GetFolder and CreateFolder.

Note 4: Pure WMI.

WMI stands for Windows Management Interface, in practice this means the script’s direct line to the operating system’s information store.  In logon scripts, you may have seen CreateObject("wscript.network"), well here with WMI, the key object is winmgmts.   Windows, or to be precise – winmgmts, knows about WIN32_xyz objects, for example, printers, computers or disks.  In our case, the object that we are interested in is the event log – to be precise WIN32_NTLogEvent.  Incidentally a good scripting program like VBsEdit will show you all these WMI objects and assist you in interrogating them.

Note the tiny word ‘Set’.  So often in VBScript the ‘Set’ command is essential to create, form or hold the object you are working on.

‘Impersonate’ sets the security credentials, in this case just accept that we use the default security settings.

The operating system, and its front end – the registry are huge places.  "\root\cimv2" tells WMI where to connect, or where to begin, in its search for the winmgmts objects.

Col or ColLoggedEvents means collation rather like a collection.  This instruction makes sense for Event Logs which have zillions of properties.  Think of col as part of the mechanism to extract information and write it to a file.

With scripting, each and every word is important, here we see an SQL transact type statement:
"Select * from Win32_NTLogEvent Where Logfile = ‘System’.  I would like to draw your attention to the ‘Where’.  What is happening is that the script is searching through the System Log as opposed to the Application or Security log.  Useful information if you wanted to amend my script.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds’ Orion performance monitor will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

Note 5: strFile section.

The scripting work is practically finished, all that is left is a logic or business decision about which properties to record in strFile.  In cases where you are not interested in a particular property, simply comment out the lines, or be ruthless and just delete the offending line.

So much of the power of a script, any script, comes from the ability to mechanically cycle through data.  Here we employ not the simple For… Next loop, but the more advanced, For EACH …. Next loop.

In order to filter the data, we have one of the oldest. but most versatile commands, ‘If  Then… End If.  Remember that in our featured script we only want a specific Event ID, a number held by the intNumberID variable, perfect for an If statement.  (Just remember that End If.)

The final method featured by this script is:  .writeline.  Our script needs to be instructed what to do with the objEvent property; writeline provides that link and outputs the events to strFile.  If you remember, strFile is the variable that holds the filename for the script output.

Note 6.  Monitor Magic

Should you find this scripting too much, then why not see what tools4ever have to offer.  With Monitor Magic you can automate Event Collection and so much more, well worth a look….

Guy’s Challenges

If you accept these 3 challenges then you may wish to create a family of text files by adjusting the strPath, for example

strFileName = "\Event9x.txt"

1) Try different IDs

Why not open up your event logs, and research interesting ID numbers.  Armed with this information, amend this line

intNumberID = 12

For example, you could try:   intNumberID = 36    (System time)

or 2,3,4, or 9 all of which are about Print information.

2) Adjust the strFile output

You could also try un-commenting some of the ‘ strFile.WriteLine    references, for example:

‘strFile.WriteLine ("Message: " & objEvent.Message)

3)strComputer = "."

strComputer = "."  Refers to the current computer, you could try amending this to different computer, for example:
strComputer = "server1"
(Assuming server1 is the name of an actual server on your network)

WMI Tip  For much more on WMI, see my WMI Section here.

Summary

Winmgmt opens up a whole new scripting area.  Thanks to Winmgmt, we can look ‘under the bonnet’ at operating system objects, for example, event logs.  This week’s VBscript outputs the information about event IDs to a text file.

See More Eventlog VBScripts

• WMI Eventlog  • Windows 8 Event Viewer  • Import Users From AD – CSVDE Tool

• PowerShell Eventlog  • Ezine 6 Eventlogs  • Ezine 39 Eventlog WMI  •Ezine 95 WMI Eventlog

VBScript Eventlog  • Ezines  • Free Log and Event Management Tool   • Tool Kit