Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a batch file delete itself?

Is it possible to make a batch file delete itself?

I have tried to make it execute another file to delete it but this did not work.

Does any one know how I could do it?

The batch file I am using is elevated. My OS is Windows 7 32 bit.

like image 384
09stephenb Avatar asked Dec 02 '13 13:12

09stephenb


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.

Can a script delete itself?

Only when the last program closes its handle does the file really get deleted. So, in a sense, yes, a shell script can delete itself, but it won't really be deleted until after the execution of that script finishes.

How do I force delete a batch file?

Force delete using WindowsWith the command prompt open, enter del /f filename , where filename is the name of the file or files (you can specify multiple files using commas) you want to delete.


2 Answers

npocmaka's answer works, but it generates the following error message: "The batch file cannot be found." This isn't a problem if the console window closes when the script terminates, as the message will flash by so fast, no one will see it. But it is very undesirable if the console remains open after the script terminates.

The trick to deleting the file without an error message is to get another hidden process to delete the file after the script terminates. This can easily be done using START /B to launch a delete process. It takes time for the delete 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 

You can simply use a CALLed subroutine if you are worried about SHIFT trashing the %0 value.

call :deleteSelf&exit /b :deleteSelf 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" 

The returned ERRORLEVEL will be 0 because DEL is the last command and it always clears the ERRORLEVEL.

If you need to have control of the ERRORLEVEL, then something like

(goto) 2>nul & del "%~f0" & cmd /c exit /b 10 
like image 51
dbenham Avatar answered Sep 29 '22 11:09

dbenham


( del /q /f "%~f0" >nul 2>&1 & exit /b 0  ) 

Set this at the end of the script. (might not work if SHIFT command is used)

like image 24
npocmaka Avatar answered Sep 29 '22 10:09

npocmaka