How to determine if a disk needs defragmentation?
Download
|
|
The programmatic defragmentation becomes possible in Windows Server 2003, or later operating system.
It may be performed on a local or a remote server. Windows XP workstation may also invoke
the remote defragmentation on a server. The Delphi function below determines if defragmentation is needed for the disk on the local or remote computer. The function returns boolean indicator of whether or not defragmentation is recommended. This example utilizes TWmiQuery, TWmiMethod and TWmiConnection components. The source code below creates and destroys the components on the fly, so this function may be used in console- or UI-type applications. |
// This function determines if defragmentation is needed for the
// disk on the target computer.
// When used for local host, the only required parameter is
// Volume, for example "c:"
//
// For remote computer, parameters must be:
// TargetHost: name or IP address of the host, like '10.8.36.54'
// UserName: name of the user, may include domain, like 'MOON\Administrator';
// Password: the user's password.
// Volume: the volume to check for defragmentation need, for example "c:"
function IsDefragmentNeeded(TargetHost, UserName, Password, Volume: string): boolean;
var
vConnection: TWmiConnection;
vQuery: TWmiQuery;
vMethod: TWmiMethod;
vSQL: string;
vResult: integer;
begin
Result := false;
vConnection := TWmiConnection.Create(nil);
vQuery := TWmiQuery.Create(nil);
vMethod := TWmiMethod.Create(nil);
vQuery.Connection := vConnection;
vMethod.WmiObjectSource := vQuery;
try
vConnection.MachineName := TargetHost;
vConnection.Credentials.UserName := UserName;
vConnection.Credentials.Password := Password;
// try to connect. It may fail if the destination computer does not have
// WMI (like windows 95, 98, NT without WMI core installed), or
// if the provided credentials are not valid
try
vConnection.Connected := true;
except
Exit;
end;
vSQL := 'select * from Win32_Volume where name = "' + volume + '\\"';
vQuery.WQL.Add(vSQL);
vQuery.Open;
if not vQuery.EOF then
begin
vMethod.WmiMethodName := 'DefragAnalysis';
vResult := vMethod.Execute;
if vResult = 0 then
Result := vMethod.OutParams.ParamByName('DefragRecommended').AsBoolean
else writeln(vMethod.LastWmiErrorDescription);
end else
begin
writeln('Could not find volume ' + volume);
end;
finally
vMethod.Free;
vQuery.Free;
vConnection.Free;
end;
end;
|