How to programatically enable System Restore monit

2019-09-20 05:39发布

问题:

I found a code that enables System Restore monitoring, but it's for C# and I need to convert it to Delphi. Here's the code:

ManagementScope scope = new ManagementScope("\\\\localhost\\root\\default");
ManagementPath path = new ManagementPath("SystemRestore");
ObjectGetOptions options = new ObjectGetOptions();
ManagementClass process = new ManagementClass(scope, path, options);
ManagementBaseObject inParams = process.GetMethodParameters("Enable");
inParams["WaitTillEnabled"] = true;
inParams["Drive"] = osDrive;
ManagementBaseObject outParams = process.InvokeMethod("Enable", inParams, null);

Could anyone help me to convert the above code to Delphi ?

回答1:

The following function returns True if the System Restore monitoring of a specified drive has been enabled, False otherwise. As the input ADrive parameter specify the full drive path to be monitored. When this parameter is the system drive, or an empty string, all drives will be monitored. This function does not wait for monitoring to be enabled completely before it returns. Instead, it returns immediately after starting the System Restore service and filter driver:

function EnableSystemRestore(const ADrive: string): Boolean;
var
  WbemObject: OleVariant;
  WbemService: OleVariant;
  WbemLocator: OleVariant;
begin;
  Result := False;
  try
    WbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
    WbemService := WbemLocator.ConnectServer('localhost', 'root\DEFAULT');
    WbemObject := WbemService.Get('SystemRestore');
    Result := WbemObject.Enable(ADrive) = S_OK;
  except
    on E: EOleException do
      ShowMessage(Format('EOleException %s %x', [E.Message, E.ErrorCode]));
    on E: Exception do
      ShowMessage(E.Classname + ':' + E.Message);
  end;
end;

And the usage:

procedure TForm1.Button1Click(Sender: TObject);
begin;
  if not EnableSystemRestore('D:\') then
    ShowMessage('Failed!')
  else
    ShowMessage('Succeeded!');
end;