55 Votes

Batch Script: Delete File if it exists

Question by Guest | Last update on 2021-04-06 | Created on 2016-09-21

I have a Windows batch script (.bat) in which an application is executed that creates a file. The program cannot handle a situation in which the corresponding file is already existing.

Therefore, I would like to check whether the file already exists and delete it if necessary before executing the application.

Is this possible using a command within my batch script? And if so, how to do that?

13Best Answer41 Votes

Within a batch script, "IF EXIST" can be used to check whether a file exists. Furthermore, with "DEL /F" you can delete a file.

The /F ensures that even readonly files can be deleted.

Accordingly, the command could look like that:

IF EXIST test.txt DEL /F test.txt

If the file test.txt exists, the DEL command will be executed and the file to be deleted.

If you do not want to repeat your filename, you can also work with variables:

SET MYFILE="c:\test.txt"


In this example, we are setting the variable "MYFILE" which can be later accessed with %MYFILE%.
Last update on 2021-04-06 | Created on 2016-09-21

ReplyPositive Negative
-15 Votes

I've used this with mixed results:

(mixed because I've had both complete and partial results, and I've tried with and without the quotes, and also tried making the /s the last entry on the line. Am I missing something simple (possible), or could this have something to do with a WIN10 64bit file system that contains long file names in folders and files? One of my trees of mp3's has over 7500 files in 150 directories and this command launched at the top just wont fully recurse in this kind of tree. System folder and file attributes A H S R are NOT involved.

@echo off
IF EXIST "*.jpg" DEL "*.jpg" /s

To satisfy curiosity I'm trying to get directory trees of mp3 files free of Album and Folder image files. They are are small files but eat up sectors wasting space and making scrolling through the directories in the path a longer process than it needs to be. Media players seem to place these image files on the hard drive when the mp3 is played, and because they're already in the MP3 they're redundant and not necessary outside of the mp3 file.
2018-10-31 at 00:02

ReplyPositive Negative

Related Topics

Rename File to its Folder Name

Tutorial | 0 Comments

PHP: File Download Script

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.


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