背景
我一直在使用Win32_DiskDrive查找闪存(USB盘,SD卡等),但是在其他计算机上进行了一些测试后,我注意到它们并不总是被发现。因此,我使用Win32_LogicalDisk,由于它具有DriveType,我不必关联两个类(例如分区)来首先查找驱动器,然后查找它们的驱动器字母。
问题在于,外部硬盘在LogicalDisk中被检测为DriveType 3(本地磁盘),而在DiskDrive的Capabilities中没有7(支持可移动媒体)。因此,我无法区分内部和外部驱动器。
问题
如何使用LogicalDisk(或者如果你真的需要,使用DiskDrive)或第三方工具区分内部和外部硬盘。
好的,问题已经得到解答!
如果有人感兴趣,这是代码。
program GetWMI_USBConnectedInfo;
{$APPTYPE CONSOLE}
uses
Windows,
Classes,
ActiveX,
Variants,
SysUtils,
WbemScripting_TLB, // Using the .pas supplied by the wrapper as it seems to be the XP version of 1.2
magwmi,
magsubs1;
function CheckType(Str: string): boolean;
var
I: Integer;
Str2: string;
begin
Result := False;
for I := 1 to Length(Str) - 1 do if Str[I] = '\' then begin
Str2 := Copy(Str, 1, I-1);
Str2 := LowerCase(Str2);
if (Str2 = 'usbstor') or (Str2 = 'flashmedia') then
Result := True;
Break;
end;
end;
procedure GetUSBDiskDriveInfo;
var
I, II, III: Integer;
Start, Stop, Freq: Int64;
instances, instances2, instances3: integer ;
WmiResults, WmiResults2, WmiResults3: T2DimStrArray ;
errstr: string ;
begin
QueryPerformanceFrequency(Freq);
QueryPerformanceCounter(Start);
try
MagWmiGetInfoEx('.', 'root\CIMV2', '', '', 'SELECT * FROM Win32_DiskDrive', WmiResults, instances, errstr);
for I := 1 to instances do begin
MagWmiGetInfoEx('.', 'root\CIMV2', '', '', 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID=''' + WmiResults[I, 12] + '''} WHERE AssocClass = Win32_DiskDriveToDiskPartition', WmiResults2, instances2, errstr);
for II := 1 to instances2 do begin
MagWmiGetInfoEx('.', 'root\CIMV2', '', '', 'ASSOCIATORS OF {Win32_DiskPartition.DeviceID=''' + WmiResults2[II, 11] + '''} WHERE AssocClass = Win32_LogicalDiskToPartition', WmiResults3, instances3, errstr);
for III := 1 to instances3 do begin
if CheckType(WmiResults[I, 32]) or (Pos('7', WmiResults[I, 3])>0) then begin
Write(WmiResults3[III, 4]);
Write(WmiResults3[III, 39]);
Writeln;
end;
end;
WmiResults3 := nil;
end;
WmiResults2 := nil;
end;
WmiResults := nil;
except
Writeln;
Writeln('error: '+errstr);
end;
Writeln;
QueryPerformanceCounter(Stop);
if (Freq > 0) then
Writeln('It took ' + FormatFloat('0.#0', (Stop-Start) / Freq) + ' seconds to complete.');
end;
begin
try
CoInitialize(nil);
GetUSBDiskDriveInfo;
Readln;
CoUninitialize;
except
on E:Exception do begin
CoUninitialize;
Writeln(E.Classname, ': ', E.Message);
Readln;
end;
end;
end.
还有一件事!
这可能算是一个不太规范的处理方法,但我在MagWmiGetInfoEx(即magwmi中的第298行)中注释掉了这一部分内容,以使它能够正常工作:
// if Pos ('SELECT', Arg) = 1 then
wmiObjectSet := wmiServices.ExecQuery (Arg, 'WQL', wbemFlagReturnImmediately, nil)
// else
// wmiObjectSet := wmiServices.InstancesOf (Arg, wbemFlagReturnImmediately or
// wbemQueryFlagShallow, nil)
;