WQL syntax: DiskDriveToDiskPartition with a LIKE o

2019-08-01 23:15发布

问题:

So I'm trying to match up physical drives to partitions to drive letters, and DiskDriveToDiskPartition seems like a good candidate for doing that, but I'm struggling to get the query to work like I want it to:

I've used the WMI Query Builder to create the gist of the query:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", 
    "SELECT * FROM Win32_DiskDriveToDiskPartition WHERE 
    Antecedent = \\\\localhost\\root\\cimv2:Win32_DiskDrive.DeviceID="\\\\\\\\.\\\\PHYSICALDRIVE3""); 

For starters, Visual Studio tells me that this isn't a valid query as it has too many \ characters in it, plus there are illegal quotes that need to be sorted. Secondly, I'd like to simply the WHERE clause to just read

WHERE Antecedent LIKE \"%" + physicalDriveID + "%\" 

The idea being to pass it a PHYSICALDRIVE variable, but all I get is Invalid Query errors.

Any pointers in the right direction on this one?

Either getting the WMI Query Builder to run or getting my LIKE clause to run would be really helpful!

回答1:

An answer is probably a long time coming but for the benefit of anyone still interested this was the solution I came up with. The trick is to make use of the ASSOCIATORS OF syntax of the WMI query. This way we can effectively JOIN the DeviceID to partitions.

using (ManagementObjectSearcher search = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"))
{
    // extract model and interface information
    foreach (ManagementObject drive in search.Get())
    {
        string antecedent = drive["DeviceID"].ToString(); // the disk we're trying to find out about
        antecedent = antecedent.Replace(@"\", "\\"); // this is just to escape the slashes
        string query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + antecedent + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition";
        using (ManagementObjectSearcher partitionSearch = new ManagementObjectSearcher(query))
        {
            foreach (ManagementObject part in partitionSearch.Get())
            {
                //...pull out the partition information
            }
        }
    }
}


标签: c# syntax wql