Search code examples
pythonwmi

How can I extract a value from a WMI object and store it in a variable?


I want to query WMI and store values in some variables. The result returns a WMI Object, I need the value on its own.

I have thought about converting the WMI Object to a string, then searching through it but that doesn't seem right.

If possible, I'd like to select a value by naming the field/caption. Similar to the way you can select a value from a JSON object.

A short example:

import wmi
c = wmi.WMI()

for baseboard in c.Win32_Baseboard(["Product"]):
  print(baseboard)

baseboard_name = baseboard["Product"]
print(baseboard_name)

In the example above, I get this error:

'_wmi_object' object is not subscriptable.


Solution

  • After some extensive Googling, I found a way to get any WMI information on its own (without the column name).

    The example below shows you how to get the motherboard model:

    import win32com.client
    
    wmi_service = win32com.client.Dispatch("WbemScripting.SWbemLocator")
    wbem_service = wmi_service.ConnectServer(".", "root\cimv2")
    baseboard_items = wbem_service.ExecQuery("SELECT * FROM Win32_Baseboard")
    
    for obj_item in baseboard_items:
      baseboard_name = obj_item.Product
    
    print(baseboard_name)