Searching with WQL

So far we’ve shown how to instantiate specific objects, such as a logical drive, and also how to enumerate all the objects of a particular class using the InstancesOf method. Knowing how to do both of these functions will take us a long way with WMI, but we are missing one other important capability: the ability to find objects that meet certain criteria.

The creators of WMI found an elegant way to handle this problem. They implemented a subset of the Structured Query Language (SQL) known as the WMI Query Language (WQL). WQL greatly increases the power of WMI by giving the programmer complete control over locating objects.

With WQL, we can even perform the same function as the InstancesOf method we used earlier. The following query retrieves all the Win32_LogicalDisk objects on the system:

select * from Win32_LogicalDisk

We can use any property available on Win32_LogicalDisk objects as criteria in our search. As an example, let’s say we wanted to find all NTFS logical disks that have less than 100 MB of available space. The query would look like the following:

select * from Win32_LogicalDisk
where FreeSpace < 104857600
and   filesystem = 'NTFS'

Pretty easy, huh? Now let’s put WQL to use. First, we need to get a WMI object to the namespace we want to query. After we’ve done that, we can call the ExecQuery method on that object and pass the WQL query to use. The next example uses the “less than 100 MB” query we just described to print out all logical disks on the local ...

Get DNS on Windows Server 2003, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.