cesbit / aiowmi

Python WMI Queries
GNU General Public License v3.0
27 stars 8 forks source link

Get properties in right order #17

Closed yoogie27 closed 2 years ago

yoogie27 commented 2 years ago

Hi, first of all, thank you very much for putting this nice library together.

I have a large monitoring software running which heavily uses WMIC. I am trying to use this library to create a drop-in replacement for WMIC.

the wmic command I am using is with delimiter = " = ". When I am querying something like "select DisplayName, Name, State from Win32_Service", I get something like this:

CLASS: Win32_Service
DisplayName = Name = State
Print spooler = spooler = Stopped
...

But when I run this same query with this library, I get the properties in a random order. How can I get them in the same order as requested?

joente commented 2 years ago

The order is not completely random. WMI return properties with an order which is used by this library to create an Ordered Dictionary. It is this order which defines how the properties are returned (at least in the props dictionary). (see the order property)

For example:

...
for name, prop in props.items():
    print(name, '\n\t', prop.order)
...

Using query:

 Query('''SELECT State, Started, StartMode FROM Win32_Service''')

Returns with properties:

Started 
         0
StartMode 
         1
State 
         2

As you see this does not reflect the order on how we ask WMI the properties. Not sure why this is the case...

yoogie27 commented 2 years ago

Thanks, I have solved it for me like below, disregarding "*" queries as I don't need them in my environment.

columns = []
        cols = re.split('select', args.query, flags=re.IGNORECASE)[1]
        cols = re.split(' from ', cols, flags=re.IGNORECASE)[0]
        for c in cols.split(','):
                columns.append(c.strip())

...

                await query.start(conn, service)
                while True:
                        try:
                                res = await query.next()
                        except WbemFalse:
                                break

                        props = res.get_properties()

                        out = []

                        for key in columns:
                                for name, prop in props.items():
                                        if name.lower() == key.lower():
                                                out.append(str(prop.value))

                        print(args.delimiter.join(out))