Friday, December 24, 2010

Batch File to Delete Itself

Sometimes users of Dr.Batcher ask us how to create a batch script that is able to delete itself. It is not hard, and the example of self-destructive script is placed in Dr.Batcher's installation package.
The trick is to call command-line processor (previously known as Command.com) with instruction to delete this batch file. While the processor is working, the source batch file will be already finished. Thus the processor will be able to delete it.
This is 'theory'. Practically you are to write the following batch code. Caution: do not run this file in folders with any valueable content, it may cause its loss or destruction.
REM Self-Deleting Batch Script
REM This script will delete all files in current folder, including itself

REM Don't forget to make backup copy of all files in current forder before its execution
ECHO This script will delete everything in current folder

ECHO Terminate it to cancel the action

PAUSE
@ECHO OFF

CD ..
START CMD /C RMDIR /S /Q "%~dp0"
The logic of whole the script is situated in the last construction. It starts the command-line processor and tells it to remove the whole directory where this batch script is placed. Of course, you can write additional batch file with this command instead. Also you can use 'DEL' instead of 'RMDIR' if you want to delete only batch file itself.

3 comments:

  1. Thank You So Much For Your Helpfull Script

    ReplyDelete
  2. Yeah same as guy above, this is exactly what I needed. For the LOLs here's what I went with:

    SET /P KILLMYSELF=Shall I delete myself now? (Y/[N])?
    IF /I "%KILLMYSELF%" NEQ "Y" GOTO END

    ECHO.
    ECHO No! I don't want to die!! NOOOO!... *muffled screams*
    PING 127.0.0.1 -n 3 >NUL
    START CMD /C DEL myscript.bat /S /Q "%_dp0"
    :END
    endlocal

    ReplyDelete
  3. why don't you just use

    DEL %0

    this command deletes the batch file itself.

    ReplyDelete

Translate