WMI and CSharp (C#)Enumerate all the instances (and properties) from a class via WQL

By | November 26, 2008

In the two previous posts (Enumerate all classes from a namespace and Enumerate all Namespaces from Root) we gather enough information to enumerate namespaces and classes. In this post we are going to see how to enumerate all the instances from a class via WQL.

using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace WmiNamespace
    class Program
        static void Main(string[] args)
            //Represents the scoop for management operations
            ManagementScope ms = new ManagementScope();

            //Represents the management query
            ObjectQuery wql = new ObjectQuery("select * from Win32_DiskDrive");

            //Retrieve a collection of management objects
            ManagementObjectSearcher searcher = 
                new ManagementObjectSearcher(ms, wql);

            //Represents different collections
            ManagementObjectCollection oc = searcher.Get();

            //The enumerator of the collection
            ManagementObjectCollection.ManagementObjectEnumerator oe = 

            Console.WriteLine("This class got " + oc.Count + " instance(s)n");

            //Enumerate the collection
            while (oe.MoveNext())
                Console.WriteLine("n********* " +
                                  oe.Current.GetPropertyValue("Name") + "n");

                //Foreach of the properties existing in one of our instance
                //display the propety name and her value
                foreach (PropertyData prop in oe.Current.Properties)
                    Console.WriteLine("> " + prop.Name + " (" + prop.Value + ")");


Below is a screenshot of what I get after executing this program:

wmi Class Instance Screenshoot

Next step will be to add, update or delete instance from a class.


0 Kudos

One thought on “WMI and CSharp (C#)Enumerate all the instances (and properties) from a class via WQL

  1. Pingback: A Web Technologist Adventure » Blog Archive » WMI and CSharp (C#): Enumerate all classes from a namespace