Daniel
Daniel

Reputation: 15

Batch delete files that aren't specified

I am making a batch file to quickly delete all files in a specific folder (I have quite a few documents in many locations). I am trying to delete every file, except for the batch file that I am running it from. I am trying to use an IF NOT statement, but I can't seem to get it to work. Here is my IF statement:

if not "%%a" == *Delete.bat" (

Where %%a is the file that I am currently testing whether or not to delete it. I'm rather sure that the error is coming from the "%%a": part of the statement, however I cannot confirm this.

Note: When I run the file, it deletes everything including itself.

Upvotes: 0

Views: 67

Answers (2)

Bisccit
Bisccit

Reputation: 31

it is true that if statements cant use wildcards. to do what you want, place the wildcard in the for loop and not in the if-statement

:: to navigate to the directory of the file
Cd "%~dp0"
for /f %%a in (*.*) do (
   if not "%%a" == "delete.bat" (
       del "%%a"
))

that will do it

Upvotes: 0

Stephan
Stephan

Reputation: 56238

if can't work with wildcards. So as long as your batchfile doesn't start with a literal asterisk (unlikely, as * is not a valid character for a filename), this won't work.

Aacinis comment shows you the way to go:

if /I "%%a" neq "%~NX0" del "%%a"

"%~NX0" evaluates the Name and eXtension of your batchfile

Upvotes: 1

Related Questions