Using WMI to query the Eventlog

By patrickwellink
April 8, 2005
Comments Off on Using WMI to query the Eventlog

After some testing on various ways to query the eventlog I found that a WMI query is the easiest way to query the Eventlog of any (remote) machine. There is very little information about WMI on the internet so I thought it was nice to post this sample snippet. (If you see anything that should be improved please reply on this post)

Public Function QueryLog(ByVal ServerName As String, ByVal LogNames As String, Optional ByVal UserName As String = “”, Optional ByVal PassWord As String = “”) As Collection

‘Set up the new collection
QueryLog = New Collection

‘Set the WMI scope options
Dim oWMI_Scope As New ManagementScope
oWMI_Scope.Path.Server = ServerName
oWMI_Scope.Path.Path = “\” & ServerName & “rootCIMV2”
oWMI_Scope.Path.NamespacePath = “rootCIMV2”

‘ Use the username and passowrd if they are supplied
If UserName = String.Empty And PassWord = String.Empty Then
   oWMI_Scope.Options.Username = UserName
   oWMI_Scope.Options.Password = PassWord
End If

‘ Set impersonation level
oWMI_Scope.Options.Authentication = AuthenticationLevel.Default
oWMI_Scope.Options.Impersonation = ImpersonationLevel.Impersonate
oWMI_Scope.Options.EnablePrivileges =

‘Define the WMI query
Dim oWMI_Query As New ObjectQuery

oWMI_Query.QueryString = “SELECT * FROM Win32_NTLogEvent WHERE ” + GetLogNames(LogNames) + ” AND TimeGenerated > ‘” + LastEventTime + “‘”

‘Create the WMI search engine
Dim oWMI_Results As New ManagementObjectSearcher(oWMI_Scope, oWMI_Query)

‘ Iterate through the resulting collection
Dim oWMI_Object As Object
For Each oWMI_Object In oWMI_Results.Get()
‘ Get the Individual EventLog entries
Dim MyEventClass As New EventLogEntry(oWMI_Object)
‘ Add the Eventlogentry to the collection
‘ Check if the Time of the generated event is greater
‘ then the last time we executed the query if so update that time
If MyEventClass.TimeGenerated > LastEventTime Then
LastEventTime = MyEventClass.TimeGenerated
End If
   ‘Clean up
MyEventClass = Nothing
Next oWMI_Object

‘ Clean up
oWMI_Object = Nothing
oWMI_Scope = Nothing
oWMI_Query = Nothing
oWMI_Results = Nothing

End Function



Comments: 0

Comments are closed.

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta