Search code examples
c#wmipower-management

Why can't I instantiate the Win32_PowerMeter WMI class?


I've seen many examples of instantiating subclasses of the WMI Win32 Classes. For example, trying the query the Win32_Battery class:

using System.Management.Instrumentation;
...
ManagementClass mgmt = new ManagementClass("Win32_Battery");
ManagementObjectCollection o = mgmt.getInstances();

However, this query fails, it tells me it is an unknown class and cannot be instantiated.

What am I doing wrong?


Solution

  • Win32_PowerMeter is not in the default namespace. Sample code generated by the WMI Code Creator utility that shows the correct namespace:

        ManagementObjectSearcher searcher = 
            new ManagementObjectSearcher("root\\CIMV2\\power", 
            "SELECT * FROM Win32_PowerMeter"); 
    
        foreach (ManagementObject queryObj in searcher.Get())
        {
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("Win32_PowerMeter instance");
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("DeviceID: {0}", queryObj["DeviceID"]);
        }