roll
roll

Reputation: 117

How can I delete all the files in the current directory except one file?

I would like to delete all the files in the current directory but I want to keep one file (update.bat)

I have this script:

for /r %%i in (*) do if not '%%~ni' == 'update.bat' del %%i

It is not working as expected because it deletes all the files and the condition seems not to be take into consideration.

What is the problem in my script?

Upvotes: 0

Views: 40

Answers (1)

MichaelS
MichaelS

Reputation: 6042

You are missing one thing: if your file is called update.bat, %%~ni will return update as ~n returns only the name but not the extension. So you are checking update==update.bat which is false. Further, del %%i might cause problems if your path contains spaces. You should also avoid spaces where they are not needed. However, replace %%~ni with %%~nxi to get the name and extension and your code will work:

for /r %%i in (*) do if not '%%~nxi' == 'update.bat' del %%i

But this code is "cleaner":

for /r %%i in (*) do if not "%%~nxi"=="update.bat" del "%%i"

Upvotes: 1

Related Questions