39

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rella
  • 65,003
  • 109
  • 363
  • 636
  • 7
    So you want a batch file that doesn't show any windows, kills a process and deletes itself after completion. Just out of curiosity. Why? – Martin Smith May 22 '10 at 17:31

7 Answers7

60

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"
dbenham
  • 127,446
  • 28
  • 251
  • 390
  • 3
    I like your 2nd solution. The first will very likely work well, but I'm not sure that it is strictly guaranteed to work if `start` manages to finish its job before the current batch script interpreter finishes. I assume that any race condition is very unlikely to be a problem if the process scheduler is working decently or the system isn't under heavy load, so it's probably just a nit-pick. – Merlyn Morgan-Graham Jul 31 '16 at 05:49
  • (and by "guaranteed to work", I mean guaranteed to avoid the error message) – Merlyn Morgan-Graham Jul 31 '16 at 05:57
  • 1
    @MerlynMorgan-Graham - Absolutely it is a race condition, so you are technically correct. But it is hard for me to imagine a scenario where the timings are reversed. It might be an interesting project to try to engineer a failure – dbenham Jul 31 '16 at 11:53
  • Just used the code: `(goto) 2>nul & del "%~f0"` in a VBA generated bat file and it worked perfectly, the bat file deleted itself without error messages. – 5202456 Mar 29 '21 at 09:27
  • Does anyone know if the `(goto)` trick still works on Windows 11? It works for me on Windows 10, but got a report from a Windows 11 user mentioning the error message: "The batch file cannot be found" – djvg Sep 27 '22 at 08:15
  • 2
    @djvg - I would be shocked if it doesn't work. The `(goto)` technique only exits the batch if there are no outstanding `CALL` routines to return from. If there is an outstanding `CALL`, then `(goto)` will exit the subroutine instead of the batch, and you will (should) get the batch file not found message, regardless of Windows version. – dbenham Sep 28 '22 at 11:25
38
@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.

Community
  • 1
  • 1
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
  • 1
    Can you explan this a little bit please? What is someotherprogram.exe and what do you punt inside it? – Ricardo Polo Jaramillo Oct 10 '11 at 21:05
  • @Richard: `SomeOtherProgram.exe` could be changed to be any program. For example, `notepad.exe`. This is the program that will be killed, and it doesn't matter what that program does - this batch file doesn't care. It just uses `TaskKill` to kill a task with that exe name. Does this clear it up? If so, did you think it needs to be added to the answer? If not, please explain in more detail what parts you understand, and which you don't. – Merlyn Morgan-Graham Oct 11 '11 at 00:17
  • 2
    Thank you for answer @Merlyn. My fault, I didnt read well the question. I was figuring why do you need to kill a process to delete a bat itself. :) – Ricardo Polo Jaramillo Oct 11 '11 at 00:28
  • 6
    The batch file will delete itself just fine, but an ugly "The batch file cannot be found." error message is generated. See [my answer](http://stackoverflow.com/a/20333152/1012053) for a method to delete without error. – dbenham Dec 06 '13 at 15:29
  • You can avoid to see message "The batch file cannot be found." with replacing `ECHO ..` and `DEL ..` with `DEL "%~f0" & EXIT` – Branko Feb 10 '18 at 08:35
  • @Branko - Yes that works, but it also kills the command session, and normally kills the console. My goal was to create a solution that preserves the command session and the console. The one scenario where `del "%~f0" & exit` is useful is if the self deleting batch is launched by `cmd /c selfDeletingBatch.bat`. That preserves the console, and no error message is printed. – dbenham Aug 14 '19 at 14:13
4

You didn't mention the OS, but if this is on Windows XP Professional and you have the appropriate permissions, you can have the batch file schedule a one-shot Windows Scheduled Task to delete the file at a later time. Use the schtasks command, documented here.

Otherwise, you typically can't delete a file that is being executed, since that has the potential for all sorts of nastiness. Additionally, trying to delete an executable in use is viewed as very suspicious behavior by any number of antivirus programs, so it's likely that you would run afoul of these as well.

John Feminella
  • 303,634
  • 46
  • 339
  • 357
  • 4
    Actually, there is a surprisingly simple way to get a batch file to delete itself without error that does not require special permissions. See [my answer](http://stackoverflow.com/a/20333152/1012053) – dbenham Dec 06 '13 at 15:26
1

you could do @Merlyn's aswer

@ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
DEL "%~f0"

Now make a vbscript with this coding and save it as hidden.vbs, this vbscript will hide the batch file's window.

set w = CreateObject(“WScript.Shell”)
W.Run chr(34) & “%userprofile%\desktop\the_batch_file.bat” & chr(34), 0
set w= Nothing

Then have the batch file run this vbscript

@ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
start "path to hidden.vbs"
DEL "%~f0"

This will hide the batch file before deleting it making the error message impossible to see.

1

Just add this command at the last line of your batch file

Del batch_file_name.bat

batch_file_name.bat is the name of your batch file

Cheers

giammin
  • 18,620
  • 8
  • 71
  • 89
Hani Ludin
  • 19
  • 1
  • *@Ricardo Polo* No, it won't work because the process is locked, so unless the PID is released then the file will not delete. I actually thought that this is what's being discussed above, but *@Hani Ludin* seems to have missed this! – CriticalPoint Oct 26 '15 at 16:37
  • @CriticalPoint that does not seem to be true for batch files! It works just fine! Just when running this from the console you get an annoying `The batch file cannot be found.` message. – ewerybody Jun 23 '20 at 13:25
1

Inline next command to do the "last things" as ghost self. It can be the exit command or some other things before exiting.

@echo off
del "%~f0" && echo All's done. I must exit! && pause > nul && exit
Rukario
  • 11
  • 2
0

You could also direct the output of the DEL "%~f0" to NULL output like so...

@ECHO OFF
SETLOCAL
SET someOtherProgram=SomeOtherProgram.exe
TASKKILL /IM "%someOtherProgram%"
DEL "%~f0" > NUL
Chad Estes
  • 371
  • 1
  • 3
  • 15
  • 2
    sorry, but the discussed error message doesn't come from `del`, but because the interpreter tries to read the "next command" from the now deleted file. Your suggestion doesn't suppress that. – Stephan Mar 29 '17 at 15:14
  • I didn't get any error message when I ran it this way, but did without it. – Chad Estes Mar 29 '17 at 16:08
  • 2
    for me it's exactly the same, with or without `> nul`. As I said: the error doesn't come from `del`, so redirecting the output of `del` won't help (besides that: to suppress ERRORS, you have to redirect STDERR: `2>nul` - which won't help either.) – Stephan Mar 29 '17 at 16:15