PowerShell Ezine, Logon Scripts

Guy's Scripting Ezine 40 - WMI and Variables

Contents for Guy's Scripting Ezine 40 - WMI and Variables

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....

ˆ

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.


For a top quality, professional management system, do check out Monitor Magic

See here for more details from Tools4Ever


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

  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.  Decide if you need to make alterations to strLog and strFolder.
  3. Save the file with .vbs extension e.g. EventVar.vbs.
  4. NOTE. As last week, nothing more will happen until you dismiss the First Message box.
  5. 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"
 

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

 

Example 2 - Script to add an InputBox

Instructions

  1. Insert the Example 2 scriptlet immediately after the Dim statements of the above Example 1 EventVar.vbs.
  2. Important: ' Rem out intEventID - 37, else it will not work!
  3. Save AS with .vbs extension e.g. EventInput.vbs.
  4. 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
 

 

WMI Tip  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.

Computer Training Software - Recommended Training VideosGuy Thomas recommends Computer Training Software

Their topics and material are ideal for getting you started with VBScript.  The videos are easy to follow and you can control the pace.  Try their free demo material and then see if you want to buy the full package. See more about VB Script Training CD.


 *


Google

Webcomputerperformance.co.uk

GFi Events Manager

Guy Recommends: GFi EventsManager

Here is a solution to monitor, manage and archive thousands of events that are generated by devices across your entire network.  Get your free evaluation copy of GFI EventsManager.

 

Home Copyright © 1999-2008 Computer Performance LTD All rights reserved

Please report a broken link, or an error.