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).



Windows Management Using C# Programming

WMI CODE CREATOR

Have you heard about the WMI Code Creator tool? It is available in the Microsoft's Download center (Link below) and it provides you a good look at what is available in the WMI classes and its object model. It's free to use, and yes, it creates code for you--including the WQL queries. The functionality of the tool to generate code that runs on the local computer, remote computer is commendable. This option is available under the Target Computer option.

The "Query for date from a WMI class" provides you the list of Namespaces, and the classes. It generates the code for you when you select the class and the property that you need. Go to the Target Computer to select the environment under which you want the code to run in.

Below are the screenshots:

[code3.jpg]
Figure 3

You can use the last textbox to narrow the scope of the query and it gets updated in the Query to the right.

[code4.jpg]
Figure 4

The Code Language option provides the flexibility of generating the script in C# , Visual Basic .NET and Visual Basic Script.

[language5.jpg]
Figure 5

Do not forget to check the last tab "Browse the namespaces on this computer" that is loaded to a great extent.

[browse6.jpg]
Figure 6

The WMI Code creator also provides you the class file in C#, which lets you know the depth of WMI query model itself. The data that appears in the screens are fetched using the WMI Queries.

WMI Code Creator can be downloaded from the Microsoft Download Center.

Scope for improvement

WMI is a vast topic to showcase the concrete stuff that can be accomplished. It just works on the typical mindset of creating useful applications that arise on the need. The potential for WMI is huge in terms of the adminstration and maintenace of applications.

Resources Win32 classes
WMI Classes
Connecting to WMI on a Remote computer
Windows Management Instrumentation

Related Articles





About the Author

Srinath M S

I would love to leave a footprint in this flat world

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds