Python WMI querying with variable query text

1

I'm new to Python (and coding in general) and I'm working my way through the WMI module. What I am looking for is a way to query WMI for event log errors filtered for date.

For example, if I do the following, it works:

events = userwmi.query("Select * from Win32_NTLogEvent where Type='error' AND TimeWritten='20120806000000.000000-000'")

If I do this:

q_text = "Select * from Win32_NTLogEvent where Type='error' AND TimeWritten='20120806000000.000000-000'"
events = userwmi.query(q_text)

It fails with the following error:

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    events = user.query(q_text)
  File "C:\Python27\lib\site-packages\wmi.py", line 1009, in query
    return [ _wmi_object (obj, instance_of, fields) for obj in self._raw_query(wql) ]
  File "C:\Python27\lib\site-packages\win32com\client\util.py", line 84, in next
    return _get_good_object_(self._iter_.next(), resultCLSID = self.resultCLSID)
com_error: (-2147217385, 'OLE error 0x80041017', None, None)

The query was syntactically invalid. I'm guessing that's because rather than passing the text as is, query() is being passed an object representing the text? I've also tried userwmi.query(wql=q_text) to explicitly specify the keyword argument being used.

My goal is to use the datetime module to get the current date at runtime, then construct a date string one month prior (taking into account leading zeroes and year changes if necessary), then construct a WQL statement that takes the new date. Right now I can construct the date according to the format above, combine that with the rest of a query statement and print the complete statement. I can manually copy that statement and paste it into the query() method and run it successfully.

Is there any hope for me here?

python
wmi
asked on Stack Overflow Aug 10, 2012 by paidhima

1 Answer

0

I'm going to answer my own question here: string encoding. By building the string and then encoding it as utf-8 everything works.

answered on Stack Overflow Aug 12, 2012 by paidhima

User contributions licensed under CC BY-SA 3.0