Contents for Guy’s Scripting Ezine 40 – WMI and Variables
- This Week’s Secret
- Recap: WMI and Event Logs
- Example 1 Script to Introduce Variables
- Example 2 Script to add in InputBox
- Summary
♣
This Week’s Secret
From where I am sitting, it’s crystal clear that WMI scripting will be a growth area for the foreseeable future. Take my advice and do not waste a chance to improve your knowledge of VBScript in general and winmgmts in particular. Last week’s theme was let’s create a useful script which will filter the Event Viewer, this week’s theme is let us enjoy ourselves and learn a few scripting tricks.
This week I am going to indulge my secret passion for variables. What I want to do is create scripts which are more flexible for the user and more exciting for we the code writers. How will we improve upon last week’s WMI scripts? By introducing choices, even decisions, for the user. Which method will we use? Firstly by incorporating more variables and secondly by adding an InputBox to give interaction between our users and the script.
Now I hope that you would like to accept my scripting challenge. However, if you need a quick ‘off the shelf’ solution, 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 Recommends: The Free IP Address Tracker (IPAT)
Calculating IP Address ranges is a black art, which many network managers solve by creating custom Excel spreadsheets. IPAT cracks this problem of allocating IP addresses in networks in two ways:
For Mr Organized there is a nifty subnet calculator, you enter the network address and the subnet mask, then IPAT works out the usable addresses and their ranges.
For Mr Lazy IPAT discovers and then displays the IP addresses of existing computers. Download the Free IP Address Tracker
Recap: WMI and Event Logs
WMI – Windows Management Interface helps us retrieve information on virtually every aspect of the operating system. This week, the event logs will act as a vehicle for our scripts, WMI will allow us to ‘home in’ on those Event IDs that are of most interest.
If you remember, the engine for extracting these event logs is winmgmts.
Set objWMI = GetObject("winmgmts:" _
Whereas the output of the script is handled by
Set objFso = CreateObject("Scripting.FileSystemObject") and objFile.writeline.
Guy Recommends: Tools4ever’s UMRA
Tired of writing scripts? The User Management Resource Administrator solution by Tools4ever offers an alternative to time-consuming manual processes.
It features 100% auto provisioning, Helpdesk Delegation, Connectors to more than 130 systems/applications, Workflow Management, Self Service and many other benefits. Click on the link for more information onUMRA.
Example 1 Script to Introduce Variables.
Scenario:
Suppose you wish to control the file name, to be specific, you wish to create a filename that reflects the Event ID, so if you are interested in ID 37, then file will be called EventID37.txt. The solution is to introduce a variable called: intEventID.
Warming to this variable them, I would next like to add a variable by the name of strLog, now we have control over which Event Log to trawl for the intEventID. If you are interested in the ‘Security’ log, then change the value of strLog, else accept my default of ‘System’.
As you may know, I like to build scripts up gradually, but at last we reach the finale, the complete path. What we do is join strLog to intEventID (concatenated with &). Actually this opens up a can of worms because strLog has to be surrounded by single speech marks. For example
strLog = Security, will fail later in the script so it hast to be in special single quotes: strLog = ‘Security’. Once again you always learn more when things go wrong – as I found out to my cost.
Instructions
- Pre-requisites. For this script to work, you need any modern operating system Windows 2000, 2003 or XP.
- Copy and paste the script below into notepad. Important: Check the Variables section of the script. Decide if you need to make alterations to strLog and strFolder.
- Save the file with .vbs extension e.g. EventVar.vbs.
- NOTE. As last week, nothing more will happen until you dismiss the First Message box.
- Use the second the message box to find your text file!
‘ EventIDVar.vbs
‘ Version 1.5
‘ Guy Thomas 8th August 2004
Option Explicit
Dim objFile, objFso, objWMI, objEvent, objFolder, colLoggedEvents
Dim strComputer, strFile, strPath, strLog, strLogPure, strFolder, strInput
Dim intEvent, intEventID, intEventID1, intRecordNum ‘ Numbers
‘ ——————————————–
‘ Set your variables
intEvent = 1
intRecordNum = 1
intEventID = 37
intEventID1 = 0
strComputer = "."
strLog = " ‘System’ "
strFolder ="C:\scripts2\"
strPath = strFolder & strLog & intEventID & ".txt"
Wscript.Echo "Path " & strPath & vbCr _
& "Event Log " & strLog
‘——————————————–
‘ Next section creates the file to store Events
‘ Then creates WMI connector to the Logs
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile = objfso.CreateTextFile(strPath, True)
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colLoggedEvents = objWMI.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = " & strLog )
‘ —————————————–
‘ Next section loops through ID properties
‘ Wscript.Echo "So far, so good, click OK then wait 30 seconds +"
intEvent = 1
For Each objEvent in colLoggedEvents
If objEvent.EventCode = intEventID Then
objFile.WriteLine ("Record No: ")& intEvent
objFile.WriteLine ("Category: " & objEvent.Category)
objFile.WriteLine ("Computer Name: " & objEvent.ComputerName)
objFile.WriteLine ("Event Code: " & objEvent.EventCode)
objFile.WriteLine ("Message: " & objEvent.Message)
‘ objFile.WriteLine ("Record Number: " & objEvent.RecordNumber)
objFile.WriteLine ("Source Name: " & objEvent.SourceName)
‘ objFile.WriteLine ("Time Written: " & objEvent.TimeWritten)
objFile.WriteLine ("Event Type: " & objEvent.Type)
objFile.WriteLine ("User: " & objEvent.User)
objFile.WriteLine (" ")
intRecordNum = intRecordNum +1
End if
IntEvent = intEvent +1
Next
Wscript.Echo "Check " & strPath & " for " & intRecordNum & " events"
WScript.Quit
‘ End of Guy’s Script
Learning Points
Note 0:
For extra information on the script, check out last week’s ezine. See Ezine 39 online
Note 1: Filename
If the file name with the strange quote marks displeases, you then try this amendment: .
strLogPure = "System"
strLog = " ‘" & strLogPure & "’ "
Warning, this tiny command drove me mad for about an hour, until I realized that the winmgmts wants precisely ‘System’ not ‘ System ‘. What I mean is that the white space was, for once, highly significant. More than that it was a pain in the backside.
Note 1b: Change the rest of the strPath commands.
If you accept this challenger, remember that Option Explicit is in operation, so check strLogPure is in the Dim section at the top. Also change
strPath = strFolder & strLog & intEventID & ".txt"
strPath = strFolder & strLogPure & intEventID & ".txt"
For much more on WMI, see my WMI Section here.
Guy Recommends: A Free Trial of the Network Performance Monitor (NPM) 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
Example 2 – Script to add an InputBox
Instructions
- Insert the Example 2 scriptlet immediately after the Dim statements of the above Example 1 EventVar.vbs.
- Important: ‘ Rem out intEventID – 37, else it will not work!
- Save AS with .vbs extension e.g. EventInput.vbs.
- Experiment with values smaller than 20 or bigger than 2000
Do
intEventID = Int(InputBox("Enter Event ID number", "Event ID", "29"))
If intEventID > 21 And intEventID < 2000 Then
strInput = True
End if
Loop until strInput = True
Learning Points
Note 1: Know your integers, for example:
intEventID must be an integer not a string. This part had me tearing my hair out for 30 minutes, until I added int(InputBox… Plain (InputBox… did not cut the mustard, you must have that INT(InputBox…
Note 2: ‘ Rem out intEventID – (Somewhere between Line 15 and line 22)
If you do not remove or at least put an apostrophe to ‘ Remark out, then you will be disappointed that your inputbox has no effect on the event that is recorded.
Below is the final script.
‘ EventIDInput.vbs
‘ Version 4.7
‘ Guy Thomas 8th August 2004
Option Explicit
Dim objFile, objFso, objWMI, objEvent, objFolder, colLoggedEvents
Dim strComputer, strFile, strPath, strLog, strLogPure, strFolder, strInput
Dim intEvent, intEventID, intEventID1, intRecordNum ‘ Numbers
Do
intEventID = Int(InputBox("Enter Event ID number", "Event ID", "29"))
If intEventID > 21 And intEventID < 2000 Then
strInput = True
End if
Loop until strInput = True
‘ ——————————————–
‘ Set your variables
intEvent = 1
intRecordNum = 1
‘ Rem intEventID
strComputer = "."
strLogPure = "System"
strLog = " ‘" & strLogPure & "’ "
strFolder ="C:\scripts2\"
strPath = strFolder & strLogPure & intEventID & ".txt"
Wscript.Echo "Path to file " & strPath & vbCr _
& "Event Log " & strLogPure & vbCr
‘ ——————————————–
‘ Next Section Creates the Folder to hold the scripts
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 objFile = objFso.CreateTextFile(strPath, True)
‘——————————————–
‘ Next section 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 = " & strLog )
‘ —————————————–
‘ Next section loops through ID properties
Wscript.Echo "So far, so good, click OK then wait 30 seconds +"
intEvent = 1
For Each objEvent in colLoggedEvents
If objEvent.EventCode = intEventID Then
objFile.WriteLine ("Record No: ")& intEvent
objFile.WriteLine ("Category: " & objEvent.Category)
objFile.WriteLine ("Computer Name: " & objEvent.ComputerName)
objFile.WriteLine ("Event Code: " & objEvent.EventCode)
objFile.WriteLine ("Message: " & objEvent.Message)
‘ objFile.WriteLine ("Record Number: " & objEvent.RecordNumber)
objFile.WriteLine ("Source Name: " & objEvent.SourceName)
‘ objFile.WriteLine ("Time Written: " & objEvent.TimeWritten)
objFile.WriteLine ("Event Type: " & objEvent.Type)
objFile.WriteLine ("User: " & objEvent.User)
objFile.WriteLine (" ")
intRecordNum = intRecordNum +1
End if
IntEvent = intEvent +1
Next
Wscript.Echo "Check " & strPath & " for " & intRecordNum & " events"
WScript.Quit
‘ End of Guy’s Script
For much more on WMI, see my WMI Section here.
Summary
WMI is the way of the future, never waste a chance to learn how VBScript can quiz the operating system. Variables offer great techniques for controlling scripts. It is useful to control a value from a central location, usually with a variable at the start of the script.
InputBox adds an extra dimension, the dimension of user interaction. With the user entering appropriate values, the script becomes more versatile.
See More WMI Scripts
• WMI • Ezines • WMI Basics • WMI PowerShell • Free SolarWinds WMI Monitor
• Ezine 9 WMI • Ezine 10 WMI • Ezine 19 WMI • Ezine 40 Variables • Ezine 48 WMI
• Ezine 52 WMI OS • Ezine 76 WMI Classes • Ezine 93 WMI • Ezine 94 WMI • Ezine 95 WMI