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.
You can just make it delete itself with del uninstaller. bat or del "%~f0" , where %~f0 represents the full path of the script.
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.
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"
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With