Today i will show a short snippet to change the letter from a drive (Volume) using the WMI. the key is use the Win32_Volume class and set the value of the DriveLetter property. this property is read/write so we can update directly the value and then call the Put_ method of the SWbemObject object.
Check out this sample project
{$APPTYPE CONSOLE} uses SysUtils, ActiveX, ComObj; procedure ChangeDriveLetter(OldDrive,NewDrive:Char); var FSWbemLocator : OLEVariant; FWMIService : OLEVariant; FWbemObjectSet: OLEVariant; FWbemObject : OLEVariant; oEnum : IEnumvariant; iValue : LongWord; begin; FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator'); FWMIService := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', ''); FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM Win32_Volume Where DriveLetter=%s',[QuotedStr(OldDrive+':')]),'WQL',0); oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant; if oEnum.Next(1, FWbemObject, iValue) = 0 then begin //Assign the New letter FWbemObject.DriveLetter:=NewDrive+':'; //Apply the changes FWbemObject.Put_(); end; end; begin try CoInitialize(nil); try //This will change the letter of the drive E to Z ChangeDriveLetter('E','Z'); Readln; finally CoUninitialize; end; except on E:Exception do begin Writeln(E.Classname, ':', E.Message); Readln; end; end; end.
Pingback: Change the drive letter using WMI and Delphi