Thursday 14 August 2008

Windows Management Instrumentation (WMI) queries

Often when coding you need to access the configuration of the server that your software is running on. This might be to determine if a particular device is connected or just to provide remote support information about the machine that the problem occured on.

Microsoft have built a feature called WMI into the Windows Driver Model. This provides an interface which you can query (using WMI queries) to access information about the system and it's components.

.NET provides a namespace (System.Management) that contains classes to query and access the results returned. The example below shows a simple example of using a query in C# to access Drive information on a specific machine.
using System.Management;

public static void DisplayDrives()
{
ManagementScope scope = new ManagementScope("\\\aMachine\\root\\cimv2");
ObjectQuery query = new ObjectQuery(
"SELECT Name, Size FROM Win32_LogicalDisk where DriveType = 3"
);
//N.B. 3 = local fixed drives ONLY

ManagementObjectCollection
drives = query.Get();
foreach(ManagementObject drive in drives)
{
Console.WriteLine(string.Format("Drive:{0} Size={1}",
drive["Name"].ToString(), drive["Size"].ToString()));

}
}
As you can see it's quite straightforward to use. However, one of the problems I have come across is how you know that the Win32_LogicalDisk is the object that contains information about the drives?

I use this page, which I found hidden away in the MSDN (I won't start ranting about how difficult it is to find anything in MSDN). It contains a break down of the different types of objects that are available for querying. You can even view the properties they contain.

I've just come across this application that Ben Coleman has created for running WMI queries on local or remote machines. It's quite useful for testing your WMI queries before adding them into your code.

No comments: