Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make .BAT file delete it self after completion?

How to make .BAT file delete it self after completion? I have a simple bat file that terminates a process. I want that .BAT file to delete itself.

like image 919
Rella Avatar asked May 22 '10 17:05

Rella


People also ask

Can you make a batch file delete itself?

You can just make it delete itself with del uninstaller. bat or del "%~f0" , where %~f0 represents the full path of the script.

How do I close a batch file after execution?

EXIT /B at the end of the batch file will stop execution of a batch file. use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.


2 Answers

The Merlyn Morgan-Graham answer manages to delete the running batch script, but it generates the following error message: "The batch file cannot be found." This is not a problem if the console window closes when the script terminates, as the message will flash by so fast that no one will see it. But the error message is very undesirable if the console remains open after script termination.

John Faminella has the right idea that another process is needed to cleanly delete the batch file without error. Scheduling a task can work, but there is a simpler way: use START to launch a new delete process within the same console. It takes time for the process to initiate and execute, so the parent script has a chance to terminate cleanly before the delete happens.

start /b "" cmd /c del "%~f0"&exit /b 

Update 2015-07-16

I've discovered another really slick way to have a batch script delete itself without generating any error message. The technique depends on a newly discovered behavior of GOTO (discovered by some Russians), described in English at http://www.dostips.com/forum/viewtopic.php?f=3&t=6491

In summary, (GOTO) 2>NUL behaves like EXIT /B, except it allows execution of concatenated commands in the context of the caller!

So all you need is

(goto) 2>nul & del "%~f0" 
like image 126
dbenham Avatar answered Sep 22 '22 02:09

dbenham


@ECHO OFF SETLOCAL  SET someOtherProgram=SomeOtherProgram.exe TASKKILL /IM "%someOtherProgram%"  ECHO "This script will now self-destruct. Please ignore the next error message" DEL "%~f0" 

Note that the DEL line better be the last thing you intend to execute inside the batch file, otherwise you're out of luck :)

This will print out an ugly error message, but it is benign, and the code is slightly less confusing this way. If you care a lot about getting rid of the error message, see dbenham's answer to get rid of it.

like image 37
Merlyn Morgan-Graham Avatar answered Sep 23 '22 02:09

Merlyn Morgan-Graham