Sponsors

Thursday, November 26, 2015

Get Hard Disk and Motherboard Serial With Delphi

Using the following code, you can get the built in hard disk serial number.
unit DPSysInfo;
interface
uses
ComObj, ActiveX, sysutils, variants;


Function GetHardDiskSerial():String;
Function GetMotherBoardSerial():String;

var
FSWbemLocator : OLEVariant;
FWMIService   : OLEVariant;
implementation


    function GetWMIstring(const WMIClass, WMIProperty:string): string;
    const
      wbemFlagForwardOnly = $00000020;
    var
      FWbemObjectSet: OLEVariant;
      FWbemObject   : OLEVariant;
      oEnum         : IEnumvariant;
      iValue        : LongWord;
    begin;
      Result:='';
      FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
      FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
      FWbemObjectSet:= FWMIService.ExecQuery(Format('Select %s from %s',[WMIProperty, WMIClass]),'WQL',wbemFlagForwardOnly);
      oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
      if oEnum.Next(1, FWbemObject, iValue) = 0 then
       if not VarIsNull(FWbemObject.Properties_.Item(WMIProperty).Value) then
       Result:=FWbemObject.Properties_.Item(WMIProperty).Value;
  FWbemObject:=Unassigned;
    end;

    Function GetHardDiskSerial():String;
    begin
      Result:=trim(GetWMIstring('Win32_PhysicalMedia','SerialNumber'));
    end;

    Function GetMotherBoardSerial():String;
    Begin
      Result:=trim(GetWMIstring('Win32_BIOS','SerialNumber'));
    End;
end.