Search code examples
vbscriptwmiutcwql

Comparing WMI DateTime to String in Query


I'm trying to query Win32_NTLogEvent for entries past the previous time that I ran the query. I've tried using a string variable so that I can change it every time I run the script. But I am getting a null returned for the generated collection. I've looked up what I can about WMI DateTimes and using them in comparisons. Although I have found some seemingly conflicting information (namely some sources using human readable to compare directly with UTC and others not). I've tried a UTC string and a human readable string. But neither seem to work. I'm thinking it is because I need to compare a datetime to a datetime as opposed to a string to a string. Although many sources seem to say that a string to a string would work in this case. But, even if I am right, I'm not sure how to convert the time for every object in Win32_NTLogEvent while inside the query.

Here is the relevant part of my script. The UTC that is commented out is just there because I don't want to retype the date if I have to go back to UTC:

strTimeMin = "01/01/1970/0:00:00"
'19700101000000.000000-480
Set objWMIService = GetObject("winmgmts:" _
 & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

'Querying Event Logs

Set colLoggedEvents = objWMIService.ExecQuery _
 ("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'system' AND "_
 & "Type = 'Error' AND TimeGenerated > " & strTimeMin & "")

Thanks for any help!


Solution

  • UTC strings should work fine. However, since they're strings you need to put them between single quotes in your WMI query:

    computer = "..."
    minTime  = "20140801000000.000000-000"
    
    Set wmi = GetObject("winmgmts:\\" & computer & "\root\cimv2")
    qry = "SELECT * FROM Win32_NTLogEvent " & _
          "WHERE LogFile = 'System' AND Type = 'Error' " & _
          "AND TimeGenerated > '" & minTime & "'"
    For Each evt In wmi.ExecQuery(qry)
      ...
    Next