How To Write A DOS Bat (Batch) File To Check And Delete A Folder With Contents And Then Self-Destruct?


How to write a simple bat file (DOS command batch file) to find if a directory exists and delete it with all items in it (all files and sub folders).

IF EXIST C:newf2Menol RD C:newf2Menol /s /q

Simple DOS command explanation:
IF EXIST will check the existence of the path you provide and execute the command you provide after that (to the right side of it) if the IF condition evaluates to TRUE.

Rd – this is the command we use now. This will Remove the Directory.

/s – We have also added command switch /s to tell it to delete the folder along with any sub folders and files in it. without this the RD will only delete empty folders.

/q – quiet mode. This will stop the dos prompt asking “Are you sure…” message.

How to make the bat file self-destruct?

Most of the time we wish if a bat file would do its work and disappear so the computer user cannot mess with it.

Luckily we can do this. The contents of the bat file are loaded into the memory so you can actually write a self-destruct command like below:

IF exist c:newf2checkanddelete.bat DEL c:newf2checkanddelete.bat /f

This is similar to the previous command line. Only here we use the command
DEL to delete a file.

/f – the switch /f will force the deletion of the file.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: