Please, I need a BATCH to delete all folders, except specific folders and sub-folders


New Member
I have a SSD with several partitions.
I need to work at J:\ and I need to delete everything inside J:\, except the following folders:

J:\System Volume Information
J:\Old Stuff

And the following sub-folders:

J:\Room\Main Documents
J:\Year\Origin\Part Two

After searching and reading a lot, I wrote the following code:

@echo OFF
SET "sourcedir=J:\"
SET "keepdir=System Volume Information"
SET "keepdir=$RECYCLE.BIN"
SET "keepdir=New"
SET "keepdir=Old Stuff"
SET "keepdir=Papers\Folder"
SET "keepdir=Room\Main Documents"
SET "keepdir=Year\Origin\Part"
SET "keepdir=Year\Origin\Part Two"
FOR /d %%a IN ("%sourcedir%\*") DO IF /i NOT "%%~nxa"=="%keepdir%" RD /S /Q "%%a"

Unfortunately, the code above doesn't work (it deletes everything inside J:\).
Please, I will appreciate any help.
Thank you in advance!
Well for starters you assign multiple values to the same variable so it's only going to contain the last value.
I also would not use a batch file, it was ok back in the day but you have way more usable language like powershell now.
It's best to breakdown a problem into small steps. The process would be something like this
  • Create a full path exclusion list
  • Get all directory paths in your root directory
  • If path is a partial or full match from your exclusion list, remove it from the list "to be deleted" (partial matches would be a parent directory)
  • Delete what remains