Windows Management Using C# Programming

Introduction

An extract from the Wiki page on description of “Windows Management” well describes it, “…a set of extensions to the Windows Driver Model that provides an operating system interface through which instrumented components provide information and notification. WMI is Microsoft’s implementation of the Web-Based Enterprise Management (WBEM)”.

This is a spot in which certain .NET API’s demonstrate their capability to provide simple yet powerful techniques to do the management of Windows. A better term might be Windows Management Instrumentation. In simple terms, it is a certain set of functionalities that lets you query the operating system in an uncomplicated and proficient manner. This is found to be vitally useful in Enterprise applications.

It would be undeniably worthwhile to reveal that this is highly powerful and can be found pretty useful at times. The only restriction to figure out is the “Privileges” required. If you have the mandatory permissions, then this is too easy.

And yes, you can use it on the conventional server machines where services run always.

WMI in its simplest and intricate forms can help you achieve the following:


  • Query the system to pull up statistics for its maintenance.

  • Query to control workstations from a remote workstation

  • Install operating system, drivers and troubleshoot systems from a remote machine

  • Apply notifications on a system.

  • Couple with Active directory and manage the AD.

  • View/Maintain process on a remote machine.

  • Manage windows services on servers.

  • Manage Exchange Servers and initiate backups on the Servers that host them.

  • Launch any programs on the remote machine.

  • Create a Health Monitoring System that takes care of the system. And initiate an emergency alert system to the Support team in case of a troublesome event.

WMI allows you to do simple stuff like checking if the remote system has a compact drive, to intricate stuff like Creating a Restore point on an Operating System. (Look below for the code). The interesting part is that you can query anything from the Operating system like a database.

The first and foremost example that comes to the mind and that is part of the first example on WMI is the Drives.
Select * from Win32_LogicalDisk returns you all the disk names on a computer.

You can specify the column names that you need to retrieve as well as the where clause too. For example,
Select FreeSpace, Size, Name from Win32_LogicalDisk where DriveType=1

.NET provides you with an API to do the System Management through easy queries as shown above. The required functionalities can be obtained from the System. Management assembly. This assembly includes the following objects to perform queries:


  • ManagementScope

  • ManagementObjectSearcher

  • ManagementObjectCollection

The power of WMI lies in its query language–Windows Management Instrumentation Query Language–WQL. Select * from Win32_LogicalDisk is the WQL query.

As MSDN suggests, by adding the WMI instrumentation, our application now becomes Managed Instrumented .NET application.

WMI Architecture is as below (From MSDN)



Figure 1

The code snippet below lists the classes present in the Management Namespace.


<CODE>
try
           {
               List<string> classes = new List<String>();
               ManagementObjectSearcher moSearcher = new    ManagementObjectSearcher(
                         new ManagementScope(
                         “provideTheNamespaceHere”),
                         new WqlObjectQuery(“select * from meta_class”), null);
               foreach (ManagementClass mc in moSearcher.Get())
               {
                   classes.Add(mc[“__CLASS”].ToString());
               }
           }
           catch (ManagementException mgEx)
           {
               //handle the error.            
           }
</CODE>

The Management Exceptions are represented by the ManagementException class that derives from the System.IO.Exception.

The following code snippets, for example, help you retrieve the services that are in running state and stopped state. Look at the filtering capabilities of the WQL.


<CODE>

/// <summary>
/// Gets the started services.
/// </summary>
/// <returns></returns>
public static List<string> GetStartedServices()
{
List<string> startedServices = new List<string>();
     try
     {
           ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(“SELECT * FROM Win32_Service WHERE Started = TRUE”);
           foreach (ManagementObject service in moSearcher.Get())
           startedServices.Add(string.Concat(“{0} is running at {1} “, service[“Caption”], DateTime.Now ));
     }
     catch(ManagementException me)
     {
           //handle the error.
     }
     return startedServices;
}
  
/// <summary>
/// Gets the stopped services.
/// </summary>
/// <returns></returns>
public static List<string>  GetStoppedServices()
{
List<string> stoppedServices = new List<string>();
     try
     {
       ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(“SELECT * FROM Win32_Service WHERE Started = False”);
           foreach (ManagementObject service in moSearcher.Get())
           stoppedServices.Add(string.Format(“{0} appears to be stopped at {1} “, service[“Caption”], DateTime.Now ));
     }
     catch(ManagementException me)
     {
      //handle the error.
}
     return stoppedServices;
}
</CODE>


We can also do complex stuff such as creating entries on the operating system’s settings such as the Restore Point System. The sample code snippet below creates a System Restore point.


public const string SYSTEM_RESTORE = “SystemRestore”;
     public const string CREATE_SYSTEM_RESTORE_POINT = “CreateRestorePoint”;
     public const string SYSTEM_RESTORE_POINT_DESCRIPTION = “Description”;
     public const string SYSTEM_RESTORE_POINT_TYPE = “RestorePointType”;
     public const string SYSTEM_RESTORE_EVENTTYPE = “EventType”;

     /// <summary>
     /// Creates the restore point.
     /// </summary>
     /// <returns></returns>
     public static bool CreateRestorePoint()
     {
         bool isCreated = true;
         try
         {
             ManagementClass mcProcess = new ManagementClass
             (
                  new ManagementScope(“\\\\localhost\\root\\default”),
                  new ManagementPath(SYSTEM_RESTORE),
                  new ObjectGetOptions()
             );

             ManagementBaseObject mbObjectInput = mcProcess.GetMethodParameters(CREATE_SYSTEM_RESTORE_POINT);
             mbObjectInput[SYSTEM_RESTORE_POINT_DESCRIPTION] = string.Format(“Restore point created from C# at {0}”, DateTime.Now);
             mbObjectInput[SYSTEM_RESTORE_POINT_TYPE] = 0;
             mbObjectInput[SYSTEM_RESTORE_EVENTTYPE] = 100;

             ManagementBaseObject mbObjectOutput =  mcProcess.InvokeMethod(CREATE_SYSTEM_RESTORE_POINT,   mbObjectInput, null);

             isCreated = (mbObjectInput == null) ? !isCreated : isCreated;
           }
           catch (ManagementException me)
           {
               //handle the error.
               isCreated = !isCreated;
           }
           return isCreated;
       }


The following screen shows the System Restore point created with the specified description.



Figure 2

You can find many more such code excerpts in the Microsoft Support article, “How To Use the System Restore Utility with Windows Management Instrumentation in Windows XP (295299)“. (Note that you can use the WMI code creator tool to create the equivalent scripts in C#. Read more on WMI Code Creator tool in the next section).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read