0
votes

If I execute the following command in a command/dos window

schtasks.exe /delete /tn "MMP4CDownloadCheck" /f

the result is as follows

ERROR: The specified task name "MMP4CDownloadCheck" does not exist in the system.

Is it possible to retrieve the return value(s) when running the same command from within my application (Delphi XE) using ShellExec?

I run it as follows:

AHWnd := ShellExecute(0, nil, PChar('schtasks.exe'), PChar(Params), nil, SW_HIDE);

Thank you in advance.

Regards, Pieter.

1

1 Answers

5
votes

Not with ShellExecute. Possibly with ShellExecuteEx or CreateProcess. You need to call GetExitCodeProcess and for that you need the handle of the created process.

For your specific case, perhaps it's better to avoid calling schtasks.exe and use the Task Scheduler API instead. See JclTask in the JCL.

An example usage I've found in one of my old units (for Delphi 2007):

procedure TSetupDataModule.AddDatabaseBackupTask;
var
  FileName: WideString;
  Scheduler: ITaskScheduler;
  Task: ITask;
  TaskPersist: IPersistFile;
  TriggerIndex: Word;
  Trigger: ITaskTrigger;
  TriggerData: TTaskTrigger;
begin
  OleCheck(CoCreateInstance(CLSID_CTaskScheduler, nil, CLSCTX_INPROC_SERVER, IID_ITaskScheduler, Scheduler));
  OleCheck(Scheduler.NewWorkItem(BackupTaskName, CLSID_CTask, IID_ITask, IUnknown(Task)));

  FileName := WideIncludeTrailingPathDelimiter(FDatabaseTargetDir) + BackupToolFileName;
  OleCheck(Task.SetApplicationName(PWideChar(FileName)));

  OleCheck(Task.SetWorkingDirectory(PWideChar(WideExcludeTrailingPathDelimiter(FDatabaseTargetDir))));
  OleCheck(Task.SetAccountInformation('', nil)); // run as local system

  FillChar(TriggerData, SizeOf(TriggerData), 0);
  TriggerData.cbTriggerSize := SizeOf(TriggerData);
  TriggerData.wBeginYear := YearOf(Today);
  TriggerData.wBeginMonth := MonthOf(Today);
  TriggerData.wBeginDay := DayOf(Today);
  TriggerData.wStartHour := 0;
  TriggerData.wStartMinute := 0;
  TriggerData.rgFlags := 0;
  TriggerData.TriggerType := TASK_TIME_TRIGGER_DAILY;
  TriggerData.Type_.Daily.DaysInterval := 1;

  OleCheck(Task.CreateTrigger(TriggerIndex, Trigger));
  OleCheck(Trigger.SetTrigger(@TriggerData));

  TaskPersist := Task as IPersistFile;
  OleCheck(TaskPersist.Save(nil, True));
end;

procedure TSetupDataModule.RemoveDatabaseBackupTask;
var
  Scheduler: ITaskScheduler;
begin
  OleCheck(CoCreateInstance(CLSID_CTaskScheduler, nil, CLSCTX_INPROC_SERVER, IID_ITaskScheduler, Scheduler));
  OleCheck(Scheduler.Delete(BackupTaskName));
end;