1

I run cmd.exe to move a file with Administrator rights:

ThisParams := '/K move ' + '"' + ThisSourceFile + '"' + ' ' + '"' + ATargetFile + '"';
Winapi.ShellAPI.ShellExecute(0, 'runas', 'cmd.exe', PChar(ThisParams), '', Winapi.Windows.SW_HIDE);

However, the cmd.exe process (although invisible) after execution remains active and in memory and stays visible in Task Manager.

How can cmd.exe, in this case, be automatically closed after execution?

user1580348
  • 5,721
  • 4
  • 43
  • 105
  • /k -> /c :https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cmd – Sertac Akyuz Jan 05 '20 at 17:00
  • I've tried to add the `/C` switch in various places of the parameters string. It does not work. – user1580348 Jan 05 '20 at 17:53
  • @SertacAkyuz, now I have really READ the text on the page: "/c Carries out the command specified by String and then stops." So now I have **REPLACED** /K with /C and it works. Thank you! Please create an answer which I will vote for. – user1580348 Jan 05 '20 at 18:06
  • 2
    You might consider [using `IFileOperation` with the COM Elevation Moniker](https://stackoverflow.com/questions/3271537/uac-elevate-while-using-ifileoperation-copyitem), then you don't need to shell out a separate process. – Remy Lebeau Jan 05 '20 at 19:37

1 Answers1

5

As documented /k makes the command interpreter to continue running after executing the passed command. You should instead use

/c   Carries out the command specified by String and then stops.

Sertac Akyuz
  • 54,131
  • 4
  • 102
  • 169
  • For the above case, is it possible to get a result of the `move` action? For example, if the target file exists and it is **read-only**, the `move` action fails even when cmd.exe is started with administrator rights. How can I get notified of the failure of the `move` action? – user1580348 Jan 06 '20 at 13:05
  • 1
    I created a [new question for this new problem](https://stackoverflow.com/questions/59613168/get-notified-if-cmd-exe-fails-to-successfully-move-a-file). – user1580348 Jan 06 '20 at 13:50