How to read ManagementObject Collection in WMI using C#

72,593

Solution 1

Take a look at your WMI query:

SELECT * FROM Win32_OperatingSystem

It means "get all instances of the Win32_OperatingSystem class and include all class properties". This is a clue that the resulting ManagementObjects are wrappers over the WMI Win32_OperatingSystem class. See the class description to learn what properties it has, what they mean and to decide which ones you actually need to use in your code.

If you need to iterate through all available properties without hard-coding their names, use the Properties property like as Giorgi suggested. Here's an example:

foreach (ManagementObject mo in osDetailsCollection)
{
    foreach (PropertyData prop in mo.Properties)
    {
        Console.WriteLine("{0}: {1}", prop.Name, prop.Value);
    }
}

Solution 2

Use the documentation first so you know what the property means. Experiment with the WMI Code Creator tool.

Solution 3

You can iterate through all properties using Properties Property

Share:
72,593
Shantanu Gupta
Author by

Shantanu Gupta

Debugging Minds... Looking For Learning Opportunities "Opportunities are Often The Beginning of Great Enterprise..." LinkedIn: https://www.linkedin.com/in/shantanufrom4387/

Updated on March 23, 2020

Comments

  • Shantanu Gupta
    Shantanu Gupta about 4 years

    I found a code on net and have been trying to get more information about mo[].

    I am trying to get all the information contained in ManagementObjectCollection.

    Since parameter in mo is looking for an string value which I dont know, how can I get all the values without knowing its parameter values. Or if I want to get all the indexer values related to mo in ManagementObjectCollection

    ManagementObjectSearcher objOSDetails = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
    ManagementObjectCollection osDetailsCollection = objOSDetails.Get();
    
    foreach( ManagementObject mo in osDetailsCollection )
    { 
       _osName  = mo["name"].ToString();// what other fields are there other than name
       _osVesion = mo["version"].ToString();
       _loginName = mo["csname"].ToString();
    }