There are times when I want to run a one-off executable on an end-user's machine that cleans up after itself, i.e. deletes itself without a trace. An exe can't delete itself because an exe can't be deleted while it's running. However, a batch file can delete itself, presumably because its contents get copied so the file can close before the code gets run.
So what if there was a general-purpose batch file that deletes the calling executable and then deletes itself? I couldn't find such a batch file so I made one, thinking maybe it could be useful to others. And obviously I want to see if it can be improved upon, of course.
This is particularly useful for an NSIS installer because the batch file can be embedded in the exe and then extracted.
Make sure you copy the batch file before you test it because it will delete itself!
@ECHO OFF SET filename=%~nx1 IF "%filename%"=="" GOTO:EOF TASKKILL /IM "%filename%" /F :LOOP TASKLIST | FIND /I "%filename%" >NUL 2>&1 IF ERRORLEVEL 1 ( GOTO CONTINUE ) ELSE ( ECHO %filename% is still running PING -n 6 127.0.0.1>NUL GOTO LOOP ) :CONTINUE DEL /F "%~f1" DEL /F "%~f0"
I figured the easiest way to get the path of the calling program is to just have it passed in as a parameter. The
IF "%filename%"=="" GOTO:EOF is very important because if the first parameter isn't defined then
DEL /F "%~f1" will automatically act like a * is there and try to delete the contents of the whole folder.