2014-11-15 51 views
2

我想獲取所有物理硬盤序列號(不是驅動器的批量序列號)和分區。獲取其中所有硬盤和分區的序列號

其實我使用DISKID32實現得到所有的硬盤序列號,但是這不會給硬盤分區。所以我打算使用其他一些方法。

下面的代碼給出了獲取物理硬盤的序列號,並在每個硬盤中查找分區。

ComputerName = "." 
Set wmiServices = GetObject (_ 
    "winmgmts:{impersonationLevel=Impersonate}!//" _ 
    & ComputerName) 
' Get physical disk drive 
Set wmiDiskDrives = wmiServices.ExecQuery (_ 
    "SELECT * FROM Win32_DiskDrive") 

For Each wmiDiskDrive In wmiDiskDrives 
    MsgBox "Disk drive Caption: " _ 
     & wmiDiskDrive.Caption _ 
     & VbNewLine & "DeviceID: " _ 
     & " (" & wmiDiskDrive.DeviceID & ")" 
    MsgBox "Serial number" _ 
       & wmiDiskDrive.SerialNumber 
    'Use the disk drive device id to 
    ' find associated partition 
    query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" _ 
     & wmiDiskDrive.DeviceID & "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition" 
    Set wmiDiskPartitions = wmiServices.ExecQuery(query) 

    For Each wmiDiskPartition In wmiDiskPartitions 
     'Use partition device id to find logical disk 
     Set wmiLogicalDisks = wmiServices.ExecQuery _ 
      ("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" _ 
      & wmiDiskPartition.DeviceID & "'} WHERE AssocClass = Win32_LogicalDiskToPartition") 

     For Each wmiLogicalDisk In wmiLogicalDisks 
      MsgBox "Drive letter associated" _ 
       & " with disk drive = " _ 
       & wmiDiskDrive.Caption _ 
       & wmiDiskDrive.DeviceID _ 
       & VbNewLine & " Partition = " _ 
       & wmiDiskPartition.DeviceID _ 
       & VbNewLine & " is " _ 
       & wmiLogicalDisk.DeviceID 

     Next 
    Next 
Next 

它完美地在Windows 8。但是,當我在Windows XP的PC測試我同時獲得序列號即wmiDiskDrive.SerialNumber遇到錯誤。所有其他對象正常工作。

然後,我發現這個屬性是不可用在Windows XP中,Windows Server 2003等 現在從上面的代碼我可以得到硬盤型號和分區,但我想要的序列號。

那麼我如何獲得硬盤序列號和他們的分區(應該在所有的Windows操作系統中工作)?任何想法?

+0

可能重複[獲取H/d序號(不Volumn序號)IDE和SATA(http://stackoverflow.com/questions/535902/get-hd-serial-number-not-volumn-serial-number-for-ide-and-sata) – jac

+0

@jac它不能在Windows XP中工作,而且我的問題不完全重複的問題(如我問它也爲win xp工作)。我想要獲得基於硬盤序列號的分區。所以請不要認爲它是重複的 –

+0

您可能需要第三方DLL才能在Vista /非XP專業版的計算機上獲得該代碼......或者某些低級別的C++代碼 – Plutonix

回答

0

這應該解決您的問題..

Public Function GetDriveSerialNumber(DrvL As String) As Long 

     Dim fso As Object, Drv As Object 
     Dim driveletter As String 
     Dim DriveSerial As String 
     Set fso = CreateObject("Scripting.FileSystemObject") 
     driveletter = DrvL 


      Set Drv = fso.GetDrive(driveletter) 


     With Drv 
      If .IsReady Then 
       DriveSerial = Abs(.SerialNumber) 
      Else 
       DriveSerial = -1 
      End If 
     End With 


     Set Drv = Nothing 
     Set fso = Nothing 

     GetDriveSerialNumber = DriveSerial 

    End Function 
+0

您的代碼中的序列號是音量序列號,而不是我想要的。在我的問題中,我提到我不想要音量序列號。我想要唯一的硬盤序列號。另外我想獲取硬盤中的所有分區。 –