Monday, July 30, 2007

Generating Strongly Typed WMI Classes

I have been playing around with .Net WMI class generation using the mgmtclassgen tool provided by Visual Studio 2005. This tool generates a strongly typed WMI class that can then be used to call methods for a paticular WMI class or retrieve properties. Here is an example on the usage of mgmtclassgen.exe:

mgmtclassgen Win32_Share /n root\cimv2 /l CS /p .\Win32_Share.cs /o WMITest

The first argument is the WMIClass to generate the source and the rest are optional arguments for namespace, the language to use, and what to name the file. When including a generated class in a Visual Studio project, you get the benefit of IntelliSense.

Here is an example of using a generated class in a console .Net 2.0 application:

class Program
{

static void Main(string[] args)
{
ConnectionOptions opt = new ConnectionOptions();
opt.Username = "username";
opt.Password = "password";

ManagementScope scope = new
ManagementScope("\\\\computername\\root\\cimv2", opt);

foreach (Win32_ConnectionShare obj in
Win32_ConnectionShare.GetInstances(scope, new EnumerationOptions()))
{
Console.WriteLine(new Win32_Share(scope,obj.Antecedent).Name);
Console.WriteLine(new
Win32_ServerConnection(scope, obj.Dependent).ShareName);
}
}
}


Although the class generation is a hoop to jump through, the code is cleaner than the late binding style of using an ObjectSearcher or WQL queries. I also find this approach better when I want to populate a dictionary object with the WMI objects for a specific computer I want to gather info about.

For reference about mgmtclassgen usage:

http://msdn2.microsoft.com/en-us/library/2wkebaxa(vs.80).aspx

No comments: