Library tutorials & articles

Using WMI From Managed Code

Page 3 of 3
  1. Introduction
  2. Working with WMI in .NET
  3. Modifying Objects & Running Methods

Modifying Objects & Running Methods

This article was originally published on DNJ Online
DNJ

Modifying an existing object

Let’s say we need to change the share status of our printer. In order to do that we need to find it in the repository, which we can do using a straightforward SQL query. For example, the following finds a printer with the name ‘Agfa’:

"SELECT * FROM Win32_Printer WHERE DeviceID = 'Agfa' 

To initialise the search we create a FindPrinters method. This returns a ManagementObjectSearcher:

private ManagementObjectSearcher 
FindPrinters( string printerName)
{
SelectQuery selectQuery = new SelectQuery();
//specify query
selectQuery.QueryString = String.Format(
"SELECT * FROM Win32_Printer
WHERE DeviceID = '{0}'
OR ShareName = '{1}'",
printerName, printerName);
//create new object searcher
ManagementObjectSearcher managementObjectSearcher =
new ManagementObjectSearcher(
this.managementScope, selectQuery);
return managementObjectSearcher;
}

The ManagementObjectSearcher contains all the objects which satisfy the query. We can then use its Get method to find the appropriate printerObject, modify its properties and put it back into the repository:

//check if anything found  if (managementObjectSearcher.Get().Count == 0)  {  
Console.WriteLine(String.Format(
"No printers with the name '{0}'
or shared name '{1}' found.",
printerName, printerName)); } else {
//if found: go through all found objects set sharing
foreach (ManagementObject printerObject in
managementObjectSearcher.Get())
{
// set sharing parameters
if (sharePrinter)
{
printerObject["Shared"] = true;
printerObject["ShareName"] = printerName;
}
else
{
printerObject["Shared"] = false;
printerObject["ShareName"] = "";
}
//put object back in "update only mode"
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOnly;
printerObject.Put(options);
}
}

Note that we use the options type ‘UpdateOnly’ which means ‘update an existing object only without creating a new one’.

Run a method

Let’s try renaming a printer using the RenamePrinter method of the Win32_Printer class. First we need to find an object on which to run the method, which we’ve already covered, and then we call the method. We start by specifying the method parameters, and then execute the method using InvokeMethod:

//specify method parameters  
object[] methodParameters = { newPrinterName };
foreach (ManagementObject printerObject in

managementObjectSearcher.Get())
{
...
//call method with specified parameters
object methodResult =
printerObject.InvokeMethod("RenamePrinter",
methodParameters);
//check invokation results
Int32 numericResult = Convert.ToInt32(methodResult);
if (numericResult != 0)
{
switch (numericResult)
{
case 5:
Console.WriteLine("Error: printer access denied");
break;
case 1801:

Console.WriteLine("Error: invalid printer name");
break;
default:
Console.WriteLine("Unknown error");
break ;
}
}
...
}

Note how we check the result: if 0 then the method was invoked successfully, otherwise we display the appropriate error message.

Deleting objects from repository

Again we start with an object search, and this time simply delete it with the Delete() method:

// if found: go through all found objects and delete them
foreach (ManagementObject printerObject in
managementObjectSearcher.Get())
{
printerObject.Delete();
}

So working with WMI from C#, or indeed Visual Basic .NET, is pretty straightforward, and such simplicity should make WMI very popular. It can be used, for example, in automated software testing, or when you need to know if an application has detected a new device, or to check if an application has modified a particular registry key.

Comments

  1. 18 Mar 2009 at 02:59
    Hi, This article is very nice. I became a member of this forum after reading this article. We have different approaches to manage enterprise systems (systems in remote or distriputed over network). like Windows Service, Web Service, Remote Management services. How is WMI different/better than those technologies. It will be good if you list the technologies before WMI and the difference Thanks a lot for your good work Regards, Palanivel

Leave a comment

Sign in or Join us (it's free).

Andriy Klyuchevskyy
AddThis

Related podcasts

  • A Practical Look at Silverlight 2 Part 1

    Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...

Events coming up

  • Nov 18

    15 Minutes of Fame

    Dresher, United States

    This is a yearly tradition. We select 10 of the favorite speakers from monthly meetings, code camps, and hands on labs. Each one does a 15 minute talk on their favorite .NET technology. This is our 10th anniversary so we plan a gala event with special prizes and refreshments.

We'd love to hear what you think! Submit ideas or give us feedback