delphiwmiguiddisk

How can I get the GUID of my disc partitions?


I'm using WMI to get all disk information, like drives, drive letters, etc. but I have not found out how I could get the UUID/GUID of each partition.


Solution

  • There are several WMI classes to access Disks and Partitions information:

    And these two, which relate the previous ones to each other:

    Specifically using Win32_Volume you can access the GUID of the existing partitions. You can test it from shell:

    > wmic volume get Driveletter, DeviceID
    

    You get data like this:

    enter image description here

    Using delphi, you can use some components, or one code like this (by Code Creator -Rodrigo Ruz-):

    program GetWMI_Info;
    {$APPTYPE CONSOLE}   
    uses
      SysUtils, ActiveX, ComObj, Variants;
       
    procedure  GetWin32_VolumeInfo;
    const
      WbemUser            ='';
      WbemPassword        ='';
      WbemComputer        ='localhost';
      wbemFlagForwardOnly = $00000020;
    var
      FSWbemLocator : OLEVariant;
      FWMIService   : OLEVariant;
      FWbemObjectSet: OLEVariant;
      FWbemObject   : OLEVariant;
      oEnum         : IEnumvariant;
      iValue        : LongWord;
    begin;
      FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
      FWMIService   := FSWbemLocator.ConnectServer(WbemComputer, 'root\CIMV2', WbemUser, WbemPassword);
      FWbemObjectSet:= FWMIService.ExecQuery('SELECT * FROM Win32_Volume','WQL',wbemFlagForwardOnly);
      oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
      while oEnum.Next(1, FWbemObject, iValue) = 0 do
      begin
        Writeln(Format('Description     %s',[String(VarToStrDef(FWbemObject.Description, ''))]));// String
        Writeln(Format('DeviceID        %s',[String(VarToStrDef(FWbemObject.DeviceID, ''))]));// String
        Writeln(Format('DriveLetter     %s',[String(VarToStrDef(FWbemObject.DriveLetter, ''))]));// String
        Writeln(Format('DriveType       %d',[Integer(VarToStrDef(FWbemObject.DriveType, ''))]));// Uint32
        Writeln(Format('Label           %s',[String(VarToStrDef(FWbemObject.Label, ''))]));// String
        Writeln(Format('Name            %s',[String(VarToStrDef(FWbemObject.Name, ''))]));// String
        Writeln(Format('SerialNumber    %d',[Integer(VarToStrDef(FWbemObject.SerialNumber, ''))]));// Uint32
        Writeln('');
        FWbemObject:=Unassigned;
      end;
    end;
    
    begin
     try
        CoInitialize(nil);
        try
          GetWin32_VolumeInfo;
        finally
          CoUninitialize;
        end;
     except
        on E:EOleException do
            Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
        on E:Exception do
            Writeln(E.Classname, ':', E.Message);
     end;
     Writeln('Press Enter to exit');
     Readln;
    end.
    

    The result looks like this:

    enter image description here