batch-filecmdshort-filenames

Delete file with specific extension in batch file


I would like to recursively delete all files with a specific extension in a batch file.

I am aware of the following command:

del /s *.ext

However, this does on Windows also delete files with other extensions like e.g. .ext1 or .ext2 . The reason for this seems to be that the 8.3 file name of such a file ends with .ext and therefore also the files with longer extensions are matched.

I am looking for a replacement to the command above that recursively deletes all files with .ext extension but keeps files with longer extensions.


Solution

  • the where command works a bit differently (in regards to wildcards and short-names). Put a for /f loop around, and you're done. Your example would then translate to:

    for /f "delims=" %%a in ('where /r . *.ext') do ECHO del "%%a"
    

    Note: I disarmed the del command by just echoing it. Remove the ECHO after troubleshooting, when you are sure it does exactly what you want.