How to get last event (based on ID) triggered on a Windows system (WMI)

Send Us a Sign! (Contact Us!)
Word PDF XPS Text
XML OpenOffice Epub MHT

It could be useful to get the last [gs event], based on ID, on a Windows-based system through a WMI query using VBScript.

The following code will get the last event using the ID code specified in the WMI query (EventCode = '7036' in this example):

'Run the function

ShowServicesEvent

'The function
Public Function ShowServicesEvent()
Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
count = 0
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceEvents = objWMIService.ExecQuery("Select * from Win32_NTLogEvent Where Logfile = 'System' and EventCode = '7036'")
For Each strEvent in colServiceEvents
dtmConvertedDate.Value = strEvent.TimeWritten
Wscript.Echo dtmConvertedDate.GetVarDate
Wscript.Echo strEvent.Message
count = count + 1
if count <> 0 Then
Exit Function
End If
Next
End Function

Note: note that the "count" section is needed to limit the results provided by WMI Core to a unique record. This is needed because WMI queries doesn't support a "SELECT TOP {X} ..." query type.

[tweet]

The following is the version without the "LIMIT 1" code portion (pay attention to run this code through a VBScript because it could provide a lot of records using MsgBox):

Public Function ShowServicesEvent()

Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
count = 0
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceEvents = objWMIService.ExecQuery("Select * from Win32_NTLogEvent Where Logfile = 'System' and EventCode = '7036'")
For Each strEvent in colServiceEvents
dtmConvertedDate.Value = strEvent.TimeWritten
Wscript.Echo dtmConvertedDate.GetVarDate
Wscript.Echo strEvent.Message
Next
End Function

Parametric Version

ShowServicesEvent(1000)

Public Function ShowServicesEvent(evcode)
Set dtmConvertedDate = CreateObject("WbemScripting.SWbemDateTime")
strComputer = "."
evecode = evcode
count = 0
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colServiceEvents = objWMIService.ExecQuery("Select * from Win32_NTLogEvent Where Logfile = 'System' and EventCode = '" & evecode & "'")
For Each strEvent in colServiceEvents
dtmConvertedDate.Value = strEvent.TimeWritten
Wscript.Echo dtmConvertedDate.GetVarDate
Wscript.Echo strEvent.Message
count = count + 1
if count <> 0 Then
Exit Function
End If
Next
End Function

SOURCE

LINK

LANGUAGE
ENGLISH

1 thought on “How to get last event (based on ID) triggered on a Windows system (WMI)”

Comments are closed.