How to join in a WMI Query (WQL)

j00hi picture j00hi · Jul 8, 2010 · Viewed 12.3k times · Source

I want to get the serial number of the boot-harddisk via a WQL query.

The boot-partition can be retrieved using the following query:

SELECT * FROM Win32_DiskPartition where BootPartition=True

The serial number is in Win32_DiskDrive:

SELECT DeviceID, SerialNumber FROM Win32_DiskDrive

Win32_DiskDriveToDiskPartition has the mapping of Win32_DiskDrive to Win32_DiskPartition. They are mapped Win32_DiskDrive.DeviceID to Win32_DiskPartition.DeviceID in Win32_DiskDriveToDiskPartition

How can I build a WQL query that inner joins Win32_DiskPartition and Win32_DiskDrive? Do I have to use Associators or does it work with INNER JOIN?

Answer

Helen picture Helen · Jul 8, 2010

WQL doesn't support the JOIN clause. You need to use the ASSOCIATORS OF statement as you guessed. Here's an example in VBScript:

strComputer = "." 
Set oWMI = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2") 

Set colPartitions = oWMI.ExecQuery( _
    "SELECT * FROM Win32_DiskPartition WHERE BootPartition=True") 

For Each oPartition in colPartitions 

    Set colDrives = oWMI.ExecQuery( _
        "ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" _
        & oPartition.DeviceID & "'} WHERE ResultClass=Win32_DiskDrive")

    For Each oDrive in colDrives
        WScript.Echo oDrive.SerialNumber
    Next

Next

Note, however, that the Win32_DiskDrive.SerialNumber property isn't available prior to Windows Vista. So, if you want your code to work on earlier Windows versions as well (e.g. Windows XP or Windows 2000) you should consider using APIs other than WMI.


Edit: (reply to comment) Yes, you can add a nested ASSOCIATORS OF query to get the Win32_PhysicalMedia instances corresponding to the Win32_DiskDrive instances; something like this:

...
For Each oDrive in colDrives
    Set colMedia = oWMI.ExecQuery( _
        "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" _
        & oDrive.DeviceID & "'} WHERE ResultClass=Win32_PhysicalMedia")

    For Each oMedia in colMedia
        WScript.Echo oMedia.SerialNumber
    Next
Next

You haven't said what language you're using - I guess in PowerShell or C# the whole thing can be done more elegantly, but VBScript is pretty verbose.