Windows – In a batch file, how to delete all files NOT of a certain type

batch-filecmddoswindows

I'm writing a batch file that needs to delete all the files in a certain dir and all of it's subdirectories except those of a specific type.

How can I do this?

Best Answer

I wrote this batch file after a coworker asked for help with deleting all the files EXCEPT for those of certain types from a folder and all subfolders, while maintaining the directory structure. I would recommend backing up your folder before attempting this. Just open up notepad and paste the following, save it as a .bat instead of a .txt Good luck! ~Carolyn

REM Use at your own risk, it does a mass DELETE of everything!

SET /p ExcludeFiles=What file type should be kept (NOT deleted)? Type the file name(s) inside parantheses. example: (pdf) or (shp dbf shx)     
SET /p MapDrive=What drive letter is the folder in? example: c or n     
SET /p Directory=Drag the folder you would like to modify into this command prompt then press ENTER.     

%MapDrive%:
cd %Directory%

attrib +a *.* /s
echo %date%
for %%i in %ExcludeFiles% do attrib -a *.%%i /s
echo %date%
del %Directory%\*.* /s /a:a /q

echo %date%
attrib +a %Directory%\*.* /s
echo %date%