TopMenu

Administering windows machine programmatically

image courtesy 123rf.comBeing a .Net developer, Automation engineer or IT administrator we always in need of dealing with windows machine configuration and settings. Most of the time changing/updating system setting programmatically. If you’re an Automation engineer you must be using scripting language(vbscript, jscript) cause you’re in love with it, If you’re a .Net developer must be using win32 library. Being an IT administrator you may be using Powershell. All interfaces are to interact with the kernel of windows and sending/querying/invoking inbuilt methods. If you heard of WMI (Windows Management Instrumentation) or even if you didn’t then no worries you’ll know everything after reading this article about what, why and how(s) of WMI.

What is WMI?

Windows Management Instrumentation (WMI) is a scalable, extensible management infrastructure, included as part of Windows 2000 and later. An implementation of the Web-based Enterprise Management (WBEM), and based on the Common Information Model (CIM) adopted by the Distributed Management Task Force (DMTF), it includes a rich set of management data about computer systems, the operating system, and applications on a given managed system.

Purpose

Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. You can write WMI scripts or applications to automate administrative tasks on local/remote computers but WMI also supplies management data to other parts of the operating system and products, for example System Center Operations Manager, formerly Microsoft Operations Manager (MOM), or Windows Remote Management (WinRM).

Where applicable

WMI can be used in all Windows-based applications, and is most useful in enterprise applications and administrative scripts. System/IT administrators can find information about using WMI at the TechNet ScriptCenter,

WMI and .Net framework

The System.Management namespace is the WMI namespace in the .NET Framework. This namespace includes the following first-level class objects that support WMI operations:

  • ManagementObject or ManagementClass: a single management object or class, respectively.
  • ManagementObjectSearcher: used to retrieve a collection of ManagementObject or ManagementClass objects based on a specified query or enumeration.
  • ManagementEventWatcher: used to subscribe to event notifications from WMI.
  • ManagementQuery: used as the basis for all query classes.

Using these class libraries, A developer can monitor, get reports, and manage local resources seamlessly.

Writing a sample code to create a system restore point using C# programmatically:

To start writing a sample application you must know few things. There namespaces stored on the windows machine and can be found under the “root”. so all namespaces will be start with a path like “\root\DEFAULT”, “\root\CIMV2” etc. Under there namespaces there are classes available named as “Win32_Environment” or “Win32_ComputerSystem” etc. Then we have methods and properties associated with each class.

Below is the sample code that will create a system restore point.

  1. using System;
  2. using System.ComponentModel;
  3. using System.Management;
  4. using System.Windows.Forms;
  5.  
  6. namespace WMISample
  7. {
  8.     public class CallWMIMethod
  9.     {
  10.         public static void Main()
  11.         {
  12.             try
  13.             {
  14.                 ManagementClass classInstance =
  15.                     new ManagementClass("root\\DEFAULT",
  16.                     "SystemRestore", null);
  17.  
  18.                 // Obtain in-parameters for the method
  19.                 ManagementBaseObject inParams =
  20.                     classInstance.GetMethodParameters("CreateRestorePoint");
  21.  
  22.                 // Add the input parameters.
  23.                 inParams["Description"] = "Test Restore point";
  24.                 inParams["EventType"] = 100; // 100 -BeginSystemChange value
  25.                 inParams["RestorePointType"] = 0; // 0 - Application install restore point type
  26.  
  27.                 // Execute the method and obtain the return values.
  28.                 ManagementBaseObject outParams =
  29.                     classInstance.InvokeMethod("CreateRestorePoint", inParams, null);
  30.                 
  31.                 // Custom code to throw the Win32 exception for information related to the error code
  32.                 int success = Convert.ToInt32(outParams["ReturnValue"]);
  33.                 if (success != 0)
  34.                 {
  35.                     throw new Win32Exception(success);
  36.                 }
  37.                 // List outParams
  38.                 Console.WriteLine("Out parameters:");
  39.                 Console.WriteLine("ReturnValue: " + outParams["ReturnValue"]);
  40.             }
  41.             catch (ManagementException err)
  42.             {
  43.                 MessageBox.Show("An error occurred while trying to execute the WMI method: " + err.Message);
  44.             }
  45.         }
  46.     }
  47. }

The above code is handling the status codes return from InvokeMethod(). The Win32Excpetion class can return the exact meaning of the returned status code.

Run this code and when you go to the system restore window from Computer –> Properties –> System protection –> System Restore you’ll find your recently created restore point there.

SNAGHTML290c1a1c

Similarly you can also write code to restore the windows system to a previously created Restore point.

Now to help you with the Namespaces and Class search for particular action on windows there’s whole documentation available in details on MSDN.

Don’t worry, To ease the process of finding the namespace, class and method and properties info Microsoft have create an tool. This tool can also generate write code for you for a particular action. Download the WMI code generator. This tool can generate WMI programs in various languages like C#, VisualBasic, VB script etc. There’s an option available in Menu items “Code Language” choose your favorite one.

Here are few snapshots from the Tool:

SNAGHTML290de45d

image

Things to Keep in mind before you start playing:

1. Firstly before running any code against you machine. “Make sure you know what you’re doing”. I will not responsible if you break your machine changing un necessary settings.

2. This is not guaranteed that the code generated from this tool will run on all machine of windows. It might run on few machines but you might have to put some tweaks to run the code on different version of Windows operating systems.

Please leave a comment/suggestion if you read it till this point.

(images courtesy - wpclipart.com & 123rf.com)

No comments:

Post a Comment