0

I'm trying to loop through the thousands of folders I have and delete all the folders that are in a specific directory, without the specified name. Here is what I have worked on so far.

@ECHO OFF
SETLOCAL
SET "sourcedir=C:\testing\%%a\all\base\"
SET "keepfile=test.bat"
SET "keepdir=keepthisfolder"

FOR /d %%a IN ("%sourcedir%\*") DO IF /i NOT "%%~nxa"=="%keepdir%" RD /S /Q "%%a"
FOR %%a IN ("%sourcedir%\*") DO IF /i NOT "%%~nxa"=="%keepfile%" DEL "%%a"

GOTO :EOF

I've tried dozens on combinations of looping through the array, but only works when I give it an exact name. It does what I need this way, but that means doing it 1-by-1.

Lex King
  • 1
  • 1
  • It's not clear what you want to do. As it stands, the code should delete all directories except those that have a `leafname` of `keep…`, so `source\keep\\` should be retained, but the subtree `source\keep\xyz\\` would go as `xyz`<>`keep`. Consequently, source\keep\xyz\keep\\` would be deleted. This is apparently not the processing you want, but you haven't told us precisely what should[not] be deleted. Running again with `peek` would zap ALL of the directories since a leafname cannot be both `keep` and `peek`. The file delete should delete all files in source, except `test.bat` – Magoo May 06 '23 at 01:33
  • Sorry, I can give more details for sure. I am trying to delete all folders (and files inside them) that are not the directory `\...\all\base\keepthisfolder` I have folders inside `\...\all\base\` that I want deleted but I don't know their exact names since they can all be different. But they all have this One folder I want to keep. – Lex King May 06 '23 at 01:39
  • This is wrong, ```C:\testing\%%a\all\base\```. Are you trying to tell us that the `%%a` part is unknown too? If so, I would advise changing it to ```Set "sourcedir=C:\testing"```, then use ```For /D %%G In ("%sourcedir%\*") Do For /D %%H In ("%%~fG\all\base\*") Do If /I Not "%%~nxH" == "%keepdir%" RD /S /Q "%%H"```, and ```For /D %%G In ("%sourcedir%\*") Do For %%H In ("%%~fG\all\base\*") Do If /I Not "%%~nxH" == "%keepfile%" Del /F "%%H"```. – Compo May 06 '23 at 05:51

1 Answers1

0

As per my comment, if the %%a part in C:\testing\%%a\all\base\ is unknown, I would advise changing your script to:

@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion

Set "sourcedir=C:\testing"
Set "keepfile=test.bat"
Set "keepdir=keepthisfolder"

For /D %%G In ("%sourcedir%\*") Do (
    For /D %%H In ("%%~fG\all\base\*") Do If /I Not "%%~nxH" == "%keepdir%" RD /S /Q "%%H"
    For %%I In ("%%~fG\all\base\*") Do If /I Not "%%~nxI" == "%keepfile%" Del /F "%%I"
)

GoTo :EOF
Compo
  • 36,585
  • 5
  • 27
  • 39