Posted by: Cirilo Meggiolaro | 12/17/2008

Tip of the day #64 – Querying WMI information with the ManagementObjectSearcher class

Introducing the Windows Management Instrumentation

The Windows Management Instrumentation known as WMI is a feature available under all Windows based operating systems that allow us to retrieve and manage system information and manage administrative tasks using scripts. It is simple to use but powerful.

The WMI is based on classes and each class exposes several properties about the system part that has been queried.

This is a really rich set of classes and to explain all of them will be impossible. To get a full list of classes, click here! After open this link you must click on each class category to see the classes.

The .NET framework can!

Yes, you can query WMI information from your .NET application.

The .NET framework provides a full set of classes to interact with the WMI available under the System.Management namespace.

We are going to check today the ManagementObjectSearcher class that give us the possibility to execute a query to retrieve management information about services, network adapters, drives, and any other object accessible via WMI and retrieve a collection of objects.

How to…

For this example we are going to query the WMI for all services available on your local computer. We are going to display the service name, description and current status of all of them.

WMI Class

The WMI class we must to use on our example is called WIN32_Service and contains the following properties:

  • bool AcceptPause;
  • bool AcceptStop;
  • string Caption;
  • UInt32 CheckPoint;
  • string CreationClassName;
  • string Description;
  • bool DesktopInteract;
  • string DisplayName;
  • string ErrorControl;
  • UInt32 ExitCode;
  • DateTime InstallDate;
  • string Name;
  • string PathName;
  • UInt32 ProcessId;
  • UInt32 ServiceSpecificExitCode;
  • string ServiceType;
  • bool Started;
  • string StartMode;
  • string StartName;
  • string State;
  • string Status;
  • string SystemCreationClassName;
  • string SystemName;
  • UInt32 TagId;
  • UInt32 WaitHint.

Queries

WMI queries are similar to SQL statements so you must use the pattern “SELECT PROPERTYNAME FROM CLASSNAME”. You are going to use property names instead of column names and class name instead of the table name.

Now that we know the properties available, the class name, and the similarity between SQL and WMI queries, create our own query is pretty straightforward:

“SELECT Name, Description, Status from Win32_Service”

Creating our object

The ManagementObjectSearcher class accepts a string containing a WMI query as the constructor parameter.

ManagementObjectSearcher serviceSearcher = new ManagementObjectSearcher(QUERY);

Retrieving the results

The Get method executes the query and retrieves a collection of management objects. The ManagementObjectCcollection is not indexed so you may use the enumerator to loop through the items.

ManagementObjectCollection existingServices = serviceSearcher.Get();

Accessing properties

Similar to a DataRow object the property may be accessed using the following syntax:

managementobject[PropertyName];

The final method

The following code snippet shows our final method:

private static void ListAllServices()
{
    /// Declares a ManagementObjectSearcher object
    ManagementObjectSearcher serviceSearcher = null;

    try
    {
        /// Instantiates the ManagementObjectSearcher object
        /// passing as a parameter the query to be executed.

        serviceSearcher = new ManagementObjectSearcher(“SELECT Name, Description, Status FROM WIN32_SERVICE”);

        if (serviceSearcher != null)
        {
            /// Loops through all objects retrieve by the method Get.
            foreach (ManagementObject wmiObject in serviceSearcher.Get())
            {
                /// Displays the properties values
                Console.WriteLine(“Name: {0} – Description: {1} – Status: {2}”, wmiObject[“Name”], wmiObject[“Description”], wmiObject[“Status”]);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        /// Releases the object.
        if (serviceSearcher != null)
        {
            serviceSearcher.Dispose();
            serviceSearcher = null;
        }
    }
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: