如何确定磁盘的分区布局是 GPT 还是 MBR

编程

[ad_1]

我正在尝试使用驱动器盘符获取 USB 磁盘的分区布局/方案。 我想知道磁盘是 MBR 还是 GPT。 我可以使用 Powerhell,但获取信息需要很长时间。 我看过 MSFT_Disk 和 MSFT_Partition 但我不知道如何使用它们。

我尝试过的:

Dim driveLetter As String = USB1 & ":" ' Replace with your drive letter

Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_DiskPartition where DriveLetter = '" & driveLetter & "'")
For Each queryObj As ManagementObject In searcher.Get()
    Dim partitionStyle As String = queryObj("DriveType").ToString()
    If partitionStyle = "3" Then
        PartitionType = ("GPT")
        MsgBox(partitionStyle)
    ElseIf partitionStyle = "2" Then
        PartitionType = ("MBR")
        MsgBox(partitionStyle)
    Else
        PartitionType = ("NR")
        MsgBox(partitionStyle)
    End If
Next

解决方案2

首先,Win32_DiskPartition 类没有“DriveLetter”属性,该查询每次都会失败。

其次,驱动器号是逻辑磁盘,而不是物理磁盘。 单个物理磁盘可以包含多个逻辑磁盘,每个逻辑磁盘通过 Win32_LogicalDiskToPartition 类分配给一个 Win32_DiskPartition 实例。

由于 WMI 不使用 JOIN 查询,因此您必须将其重写为 ASSOCIATORS OF 查询,如下所示:

WQL
ASSOCIATORS OF {Win32_LogicalDisk.DeviceId='E:'} WHERE ResultClass=Win32_DiskPartition

此查询将为您获取指定驱动器号的 Win32_DiskPartition 对象。

解决方案1

Function GetDiskPartitionType(diskDrive As String) As String
        Dim upperCaseDiskLetter As String = diskDrive.Substring(0, 1).ToUpper()
        Dim wmiQuery As String = $"SELECT DiskNumber, GptType, MbrType FROM MSFT_Partition WHERE DriveLetter='{upperCaseDiskLetter}'"
        Dim scope As New ManagementScope("\\localhost\ROOT\Microsoft\Windows\Storage")
        Dim partitionSearcher As New ManagementObjectSearcher(scope, New ObjectQuery(wmiQuery))

        For Each partition As ManagementObject In partitionSearcher.Get()
            Dim gptType As String = partition("GptType")?.ToString()
            Dim mbrType As Integer = Convert.ToInt32(partition("MbrType"))

            If Not String.IsNullOrEmpty(gptType) Then
                Return "GPT"
            ElseIf mbrType <> 0 Then
                Return "MBR"
            Else
                Return "Unknown"
            End If
        Next

        Return "Unknown"
    End Function

[ad_2]

コメント

标题和URL已复制