Windows – Recursively delete directory except for some files in Windows

shellwindows

In Windows, I need to recursively delete a directory except for a short list of files to be kept. The files may be nested in subdirectories.

I tried making the files read-only before running "rmdir /s", but it doesn't work. Read-only files cannot be deleted directly, but they are deleted when inside a subdirectory being deleted with "rmdir /s".

Any other ideas?

Best Answer

As far as I know you really can't have it both ways -- either the delete is recursive (everything goes) or it is not recursive (you explicitly list what you want gone).

The only reason the kind of read-only trick you tried works on Unix systems is because the failure/error propagates up the tree (you can't delete something that still has children), and it would appear from your test that Windows is less particular about that.