winapiwmiautoitdisk-partitioningdrive-letter

Finding Drive Letter by Disk Number, Partition Number, and Label using AutoIt


I'm working on an AutoIt script where I have the disk number, partition number, and label, and I need to find the corresponding drive letter. I've tried several approaches, but none seem to work consistently. Here's the current code:

$query = "SELECT DriveLetter FROM Win32_DiskDriveToDiskPartition WHERE DiskNumber = " & $targetDiskNumber & _
         " AND PartitionNumber = " & $targetPartitionNumber & _
         " AND Name = '" & $targetLabel & "'"
$result = $WMBIObj.ExecQuery($query)

The variables $diskNumber, $partitionNumber, and $label are known. Can someone help me with a reliable method to find the drive letter associated with the specified disk number, partition number, and label?

I'm using the Win32_DiskPartition and Win32_LogicalDisk classes via WMI in AutoIt. The label refers to the volume label of the partition. The script should work on various Windows systems.


Solution

  • here complete solution

    Func GetSelectedDriveLetter($targetLabel)
        ; Get the selected disk number from the combo box
        Local $selectedDiskNumber = StringRegExp(GUICtrlRead($cCombo), "Disk (\d+):", 1)
    
        ; Iterate through the disk drives to find the matching disk
        For $SingleDiskDrive In $WMBIObj.ExecQuery("SELECT * FROM Win32_DiskDrive")
            If StringRegExp($SingleDiskDrive.DeviceID, "PHYSICALDRIVE" & $selectedDiskNumber) Then
                ; Find the partition with the label "UTZ_BOOT"
                For $Partition In $WMBIObj.ExecQuery("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" & $SingleDiskDrive.DeviceID & "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition")
                    For $SingleLogicalDisk In $WMBIObj.ExecQuery("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" & $Partition.DeviceID & "'} WHERE AssocClass = Win32_LogicalDiskToPartition")
                        If $SingleLogicalDisk.VolumeName == "$targetLabel" Then
                            ; Found the partition, extract the drive letter
                            Local $driveLetter = StringLeft($SingleLogicalDisk.DeviceID, 2)
                            Return $driveLetter
                            ExitLoop ; Exit the loop since we found the match
                        EndIf
                    Next
                Next
            EndIf
        Next
    EndFunc