0

I am trying to delete all folders on all drives with the above naming pattern, however only on the first folder level, i.e directly below the drive letter, like for example:

F:\this folder's name contains FOO and should be deleted

...without confirmation nor error message (e.g. in case no folders are found), with a batchfile.

I've found this: delete all folders with tmp in name using batch file and am wondering if the solution from there is a good starting point?

@echo off
set dir="c:\FOLDERLOCATION\"
FOR /D /R %dir% %%X IN (*.tmp) DO RMDIR /S /Q "%%X"
pause
exit

1 Answer 1

1

Read and follow FOR - Conditionally perform a command several times.. You could apply either FOR-Folders, or FOR-Command Results as follows:

FOR-Folders (disadvantages: case insensitive; wildcards allow no regex-like pattern so we need to run a loop more times).

@echo off
set "dir=c:\FOLDERLOCATION\"
pushd "%dir%"
::                          ↓↓↓↓                      echo for debugging
FOR /D /R %%X IN (*foo*) DO echo RMDIR /S /Q "%%~fX"
FOR /D /R %%X IN (*bar*) DO echo RMDIR /S /Q "%%~fX"
::                          ↑↑↑↑                      echo for debugging
popd
pause

FOR-Command Results in combination with findstr (advantages: findstr independently allows both case sensitive and regex-like search pattern):

@echo off
set "dir=c:\FOLDERLOCATION\"
FOR /F "delims=" %%X IN ('dir /B/S /A:D "%dir%" ^| findstr /I "foo|bar"') DO 2>NUL echo RMDIR /S /Q "%%~fX"
:: ECHO in above line merely for debugging
pause

A disadvantage is that dir list is generated statically so we need to redirect error messages using 2>NUL

3
  • Awesome! Would it be also possible to leave the batchfile running invisibly and wait for new drives to appear, like external hard drives etc., and then act on these as well?
    – David.P
    Jun 11, 2021 at 22:59
  • Btw., what does set "dir=c:\FOLDERLOCATION\" do?
    – David.P
    Jun 11, 2021 at 23:08
  • Dealing with quotes in Windows batch scripts. Define a variable as set "dir=c:\FOLDERLOCATION\" (its value does not include double quotes) and use it quoted if necessary e.g. type "%dir%%file%%ext%" (providing set "file=some file name" and set "ext=.ext")
    – JosefZ
    Jun 12, 2021 at 13:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .