How to defragment a disk?  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 method below performs defragmentation of a disk on a local or remote computer. 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 procedure defragments the specified volume 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 defragment, for example "c:" 
procedure DoDefragment(TargetHost, UserName, Password, Volume: string);
var
  vConnection: TWmiConnection;
  vQuery: TWmiQuery;
  vMethod: TWmiMethod;
  vSQL: string;
  vResult: integer;
begin
  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
      writeln('Deframenting volume ', volume, '...');
      vMethod.WmiMethodName := 'Defrag';
      vResult := vMethod.Execute;
      if vResult = 0 then
      begin
        writeln('Drive ', volume, ' sucessfully defragmented');
      end else
      begin
        writeln('Drive ', volume, ' could not be defragmented.');
        writeln('Error code: ', vMethod.LastWmiError);
        writeln(vMethod.LastWmiErrorDescription);
      end;
    end else
    begin
      writeln('Could not find volume ' + volume);
    end;

  finally
    vMethod.Free;
    vQuery.Free;
    vConnection.Free;
  end;

end;