[python-win32] wmi query.

Tim Golden mail at timgolden.me.uk
Wed Mar 26 09:59:54 CET 2008

mark.a.brand wrote:
> what about events,
> for example i only want to return  error and warning events for the last 4
> days from all logs. getting all the events and then filtering them will be
> terrribly slow.

You let WMI do the filtering. For this, since it's a non-equi
filter (you want the last 4 days) you'll have to pass the WQL
through yourself. It's still advantageous to use the wmi
module for this, even though you're producing your own query,
since it wraps the results for you as _wmi_objects and gives
you easy access to their properties, methods etc.

import wmi
import datetime

five_days_ago = datetime.date.today () - datetime.timedelta (5)
wmi_five_days_ago = wmi.from_time (*five_days_ago.timetuple ()[:-1])

# WQL won't like the line feeds. Strip them out later.
WQL = """
FROM Win32_NTLogEvent
WHERE (EventType = 1 OR EventType = 2)
AND TimeGenerated >= "%s"
""" % wmi_five_days_ago

c = wmi.WMI ()
for event in c.query (" ".join (WQL.split ())):
   print event.Logfile, \
         event.RecordNumber, \
         wmi.to_time (event.TimeGenerated)


There's some slight messiness involved in the time aspects
of this. And I realise that, although the wmi module does
have a couple of helper functions (to_time and from_time)
they don't actually play all that well with the datetime
module. Still, they do return a recognisable tuple which
you can play with. I'll try to improve them anyway.


More information about the python-win32 mailing list