Using WMI From Managed Code

Running Methods

This article was originally published on DNJ Online
DNJ Online
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.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Engineers are all basically high-functioning autistics who have no idea how normal people do stuff.” - Cory Doctorow