0

I am trying to use this to kill a running process, then delete the exe which runs that process and after that rename a file (.temp) with the same name as the deleted file and finally run it. However, I am having two problems: first one is that I am required to run this as administrator in order to be able to kill the task (I have solved this already running cmd as admin), and the second problem is that when rename is executed it says that the file already exists (but it should not because there was a delete just before). The code runs fine if you are not running the exe you want to kill, but if it is running then the said error appears.

 @echo off
    set name=%1
    taskkill /F /IM %name%
    del %name%
    ren %name%.temp %name%
    start %name%
    exit

Am I missing something in this piece of batch code? Thanks

Arturo
  • 328
  • 2
  • 13
  • 1
    Change first line to `@echo on` and replace `exit` by `pause`, run the batch file and look on the messages output. I suppose that deletion of the file fails as not found. Does `%1` specify the name of the file with file extension and full path in double quotes if path contains a space character? And `taskkill` needs some time to terminate running process. So an immediate deletion of executable file is not possible before process completely terminated. – Mofi Dec 08 '14 at 15:51
  • @Mofi After enabling echo and replacing exit by pause I see that I am getting a "Denied Access" after killing the process (which is correctly ended as the console says) The "Denied Access" belongs to the "delete" command... That's where the problem lies. The file path is set correctly (furthermore, I've already said that it works fine if the process is not running, so the path is alright). – Arturo Dec 08 '14 at 16:00
  • 1
    So the deletion is done too early after killing the process. Insert a wait of 1 second or some milliseconds between `taskkill` and `del` and check if that helps. See [Sleeping in a batch file](http://stackoverflow.com/questions/166044/). – Mofi Dec 08 '14 at 16:06
  • Yes, that solved it, although it seems a bit hacky, haha. Thanks a lot! – Arturo Dec 08 '14 at 16:11

2 Answers2

0

It can be that the delete has not entirely resolved yet. You can use MOVE instead of REN, which will overwrite the file.

davidahines
  • 3,976
  • 16
  • 53
  • 87
  • I am getting a Denied Access at move. @echo on set name=%1 taskkill /F /IM %name% move %name%.temp %name% start %name% pause – Arturo Dec 08 '14 at 16:06
0

According to @Mofi, the problem lies in the fact that the deletion is executed too early since the taskkill has not been finished yet. This was fixed by adding "timeout /t 2" between taskkill and del.

Arturo
  • 328
  • 2
  • 13