Wednesday 6 February 2008

Windows Management Instrumentation code examples

I would like to describe what Windows Management Instrumentation (WMI) is and what it can be used for. There are included examples on all covered areas.

What is WMI?

WMI is Windows management technology, it allows to manage and control local or remote computers. WMI allows you do a lot by modeling objects such as disks, processes, or other objects found in Windows systems. For each system object there is created WMI class e.g. Win32_NetworkAdapter, Win32_Directory or Win32_Process. You can use WMI classes from .NET applications and even from visual basic script.

What can WMI be used for?

  • Query for data from a WMI class (e.g. get list of processes on local or remote computer)

  • Execute a method (e.g. start a new process or or share a directory from your harddisk)

  • Receive an event (e.g. wait until specified process started )

Query for data from a WMI class

Following section contains examples of how to query for some interesting data from WMI classes.
How you can get MAC addresses of you network adapters
  ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_NetworkAdapter");

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Win32_NetworkAdapter instance");
Console.WriteLine("Caption: {0}", queryObj["Caption"]);
Console.WriteLine("MACAddress: {0}", queryObj["MACAddress"]);
}
How to get current CPU usage
  ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor");

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Win32_PerfFormattedData_PerfOS_Processor instance");
Console.WriteLine("PercentProcessorTime: {0}", queryObj["PercentProcessorTime"]);
}

Execute a method

This section shows in examples how methods of WMI classes can be used.
How can you logoff from you computer?
  ManagementClass classInstance = new ManagementClass("Win32_OperatingSystem");
// Obtain in-parameters for the method
ManagementBaseObject inParams = classInstance.GetMethodParameters("Win32Shutdown");

// Add the input parameters.
inParams["Flags"] = 0; // logoff
inParams["Reserved"] = 0;

// Execute the method and obtain the return values.
ManagementBaseObject outParams = null;
foreach (ManagementObject mo in classInstance.GetInstances())
outParams = mo.InvokeMethod("Win32Shutdown", inParams, null);

Recieve na event

This section shows how to wait until WMI event happen.
How to wait until specific process started
  WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = 'notepad.exe'");

ManagementEventWatcher watcher = new ManagementEventWatcher(query);
Console.WriteLine("Waiting for an event...");

ManagementBaseObject eventObj = watcher.WaitForNextEvent();

Console.WriteLine("{0} event occurred.", eventObj["__CLASS"]);
foreach (PropertyData pd in eventObj.Properties)
{
Console.WriteLine(pd.Name + " " + pd.Value);
}

// Cancel the event subscription
watcher.Stop();

WMI on remote computer

This section will show you how you can do WMI queries on remote computer.
How to get list of drives on remote computer
  ConnectionOptions connection = new ConnectionOptions();
connection.Username = "username";
connection.Password = "password";
connection.Authority = "ntlmdomain:domain_name";

ManagementScope scope = new ManagementScope("\\\\10.98.8.52\\root\\CIMV2", connection);
scope.Connect();

ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_DiskDrive");

ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("Name: {0}", queryObj["Name"]);
}

Useful links

  • WMICodeCreator - very useful for beginners. It can generate WMI code for C#, Visual Basic and Visual Basic Script.