Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
777 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 & "
ootCIMV2") 

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...