Score:0

Delete all folders on all drives with "foo" OR "bar" in the folder name with batchfile

jp flag

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
Score:1
th flag

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

jp flag
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?
jp flag
Btw., what does set "dir=c:\FOLDERLOCATION\" do?
JosefZ avatar
th flag
[Dealing with quotes in Windows batch scripts](https://stackoverflow.com/questions/535975/). 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"`)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.