68 Votes

Batch Script: Delete Folder if it exists

Question by Guest | Last update on 2021-04-25 | Created on 2016-10-03

I would like to program a Windows Batch Script (.BAT) in a way that it can a bit "tidy up" for me. The script should check whether some folders are existing and if this should be the case, it should remove them.

Can someone give me an advice how to implement that? I do not know much about batch scripts.

ReplyPositiveNegative
2Best Answer8 Votes

We can check whether a folder or directory is existing on our system with "IF EXIST <folder name>".

The deletion can be done with "RMDIR /S /Q <folder name>" (or also using RD or DEL alternatively).

In a batch script this can look like:

IF EXIST c:\folder RMDIR /S /Q c:\folder

If we do not want to repeat the path, for example because it is too long, we can also work with variables:

SET F="c:\folder"

IF EXIST %F% RMDIR /S /Q %F%

By the way, we are using the parameters /S and /Q here.

  • The parameter /S (standing for sub directories) cares about that also all sub folders including all files will be deleted. 
  • The parameter /Q (quiet) ensures that all will be deleted without any notification / question dialog.

If we omit the parameters, the opposite happens accordingly.
Last update on 2021-04-25 | Created on 2016-10-03

ReplyPositive Negative
Reply

Related Topics

Rename File to its Folder Name

Tutorial | 0 Comments

C#/.NET: Check if Folder exists

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.