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

Decopi

New Member
Joined
Jun 17, 2023
Messages
1
Hi,
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:\$RECYCLE.BIN
J:\New
J:\Old Stuff

And the following sub-folders:

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

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

@echo OFF
SETLOCAL
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"
GOTO :EOF

Unfortunately, the code above doesn't work (it deletes everything inside J:\).
Please, I will appreciate any help.
Thank you in advance!
 

Solution
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

Neemobeer

Windows Forum Team
Staff member
Joined
Jul 4, 2015
Messages
8,998
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.
 

Neemobeer

Windows Forum Team
Staff member
Joined
Jul 4, 2015
Messages
8,998
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
 

Solution
Back
Top