Dave Wulf
Dave Wulf

Reputation: 1

Batch delete subfolder if exist

Im desesperate for help... im trying to make simply delete search folder if exist on batch.

batch file:

@for %%i in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO @if exist %%i: @for /d /r "%%i:\" %%a in (program\logs\) do if exist "%%a" echo rmdir /s /q "%%a"

but the result is not correct

if exist "C:\%i:\program\logs\" echo rmdir /s /q "C:\%i:\program\logs\"

Upvotes: 0

Views: 111

Answers (1)

Magoo
Magoo

Reputation: 80213

Well- known bug with for /r - the directory root provided before the %%a may not be a metavariable (ie the control variable from an outer loop)

Possible workaround (untried)

for %%i in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO if exist %%i: call :sub "%%i"
....
goto :eof

:sub
set "targetdir=%~1"
for /d /r "%targetdir%" %%a in (program\logs\) do if exist "%%a" echo rmdir /s /q "%%a"
goto :eof

the goto :eof (where the colon is required) jumps over the remainder of the code in the file. CALLing the subroutine supplies "%%i" as the first parameter to the subroutine :sub (the quotes are not required in this case - but would be if the string being passed contained separators)

:sub sets a variable to the contents of the first parameter supplied; the ~ removes the quotes. Since batch replaces %var% with the contents of the variable as part of the parsing operation, it should make the appropriate substitution.

BTW - a @echo off statement at the start of a batch makes @ redundant within the file (@ means "don't echo this statement before execution)

Upvotes: 1

Related Questions