Search code examples
windowsbatch-filecmdsubdirectory

How to search/delete multiple subfolders?


I have a "clean up" batch program that sits in a parent directory & deletes certain extraneous files within the directory "tree". One function is to delete extra ".backup" save folders (just .backup, not main folders) For reference, the folder path is like:

\Parent folder (w/ my .bat)
  \Saves
    \save 1\save files
    \save 1.backup\save files
    \save 2\save files
    \save 2.backup\save files
    (etc)

I can remove the unwanted subfolders using

for /d %%x in (Saves\*.backup) do rd /s /q "%%x"

However, I want to add a check into the code to verify that the folders have actually been deleted & give correct message for success, failure, no folder, etc. outcomes.

I can do that with file deletion functions using IF EXIST/IF NOT EXIST arguments, but I'm having trouble applying these to the subfolder deletion.

I can look for files in the save folders to satisfy the EXIST/NOT EXIST arguments, but using the * wildcard in the subfolder name seems to be throwing a wrench into the works, and the program fails to detect any folders/files using that statement. However if I define a specific save folder outright, the subroutine will work perfectly.

So:

if not exist "Saves\save 1.backup\*.*" ( goto nofile )
if exist "Saves\save 1.backup\*.*" ( for /d %%x in (Saves\*.backup) do rd /s /q "%%x" )

will delete the correct folders (or give a message if no valid folders), but

if not exist "Saves\*.backup\*.*" ( goto nofile )
if exist "Saves\*.backup\*.*" ( for /d %%x in (Saves\*.backup) do rd /s /q "%%x" )
 

doesn't delete anything, & just gives my "nofile" message.

Obviously, specifying every possible save name isn't an option.

Any solutions?

p.s. to head off any extra questions: I want to [occasionally] delete these backups because the program makes a new one each time it saves.


Solution

  • You can check folder into for loop after command rd.

    for /d %%x in (Saves\*.backup) do (
      rd /q /s %%x
      if exist %%x (echo Failed) else echo Success
    )