I need to delete files of a certain type (.zip files, say) from a folder, and all of its sub-folders, using the command line. Ideally I am looking for something that can be run as a .bat file in Windows.
I know there is a /S switch for the DEL command to look in sub-folders, but to add to the challenge I need to exclude files of a certain name (‘Backup.zip’ as an example).
Is there a way to delete files recursively but exclude files of a certain name. It will not be practical in my situation to explicitly list all the file names I want to delete, only the files of the matching type I don’t want to delete.
A nice trick: make the files you want to exclude read-only!
DEL /Swill not delete read-only file.The following script does not do exactly what you want (see my remarks below) but shows you how read-only files can be used to avoid deletion.
Note: you can adapt this script in order to ignore not just a sub-folder but all files of given type:
will in effect help you to exclude all ‘xxx’ files of the current directory and all sub-directories (hence the
/Soption).Note: the ‘
> NUL‘ part is a redirection often used to hide standard output, instead of displaying it on screen.It can be dangerous if used too often (in a large loop with different paths involved, for instance) since it is a device, and like all devices (
AUX,COMn,LPTn,NULandPRN):NULin, say,C:\and after that you use it again inC:\TEMP, you’ll lose another file handle.