Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Framework  »  WMI connections made easy in VB.NET  »  Okay, I'm In. Now what?
WMI connections made easy in VB.NET
by Martin de Klerk | Published  04/24/2005 | .NET Framework | Rating:
Okay, I'm In. Now what?

Let's say you want to know what software is installed on a remote PC. In essence you send a query to the (remote) WMI server. This WMI server returns the result of that query (in this case as an ManagementObjectCollection, which is an array of ManagementObjects each representing a particular piece of software installed by the MS-Installer). The query will be coordinated by the ManagementObjectSearcher class:

    Dim myObjectSearcher as System.Management.ManagementObjectSearcher
    Dim myCollection As System.Management.ManagementObjectCollection
    Dim myObject As System.Management.ManagementObject
    myObjectSearcher = New System.Management.ManagementObjectSearcher( _
      myManagementScope.Path.ToString, "Select * From Win32_Product")
    '* execute query
    myCollection = myObjectSearcher.Get()
    '* list packages installed
    For Each myObject In myObjectCollection
        Console.WriteLine( myObject.GetPropertyValue("Caption"))

The above routine will work for any of WMI's Win32_XXXX classes, as all of these classes possess the property "Caption". For a complete list of available WMI classes, objects and namespaces, check out MSDN or see the links at the end of this article.

A note on retrieving WMI values: as these values are not type-safe ( the VB.NET compiler has no way of knowing in advance what type of data will be returned), you will have to convert certain data-types to the .NET equivalents. For instance: the property Win32_Printer.Priority is an unsigned 32 bits integer (uint32). The .NET Framework does not allow unsigned integers, so to use this value you will have to convert the value to a .NET data type:

    myPriority = Convert.ToInt32( myPrinterObject.GetPropertyValue("Priority"))

This is fine if you only make basic use of WMI, but as your use of WMI extends you'll find these coded conversions a big trouble-source and waste of typing effort. The solution comes in the form of Management Strongly Typed Class Generator (Mgmtclassgen.exe). This utility, contained in the .NET Framework Toolkit, generates an early-bound (strong typed) wrapper for the selected WMI Win32_XXXX management class to include in your project. Using this wrapper, you do not have to worry about standard conversions.

Sponsored Links