How to join in a WMI Query (WQL)

前端 未结 2 941
盖世英雄少女心
盖世英雄少女心 2020-12-19 02:02

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 Wi         


        
2条回答
  •  -上瘾入骨i
    2020-12-19 02:17

    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.

提交回复
热议问题