The problem is the first line not explicitly starting cmd.exe
with option /C
to execute the batch file once again with a separate command process with minimized window.
@echo off
if defined IS_MINIMIZED goto ClearFolders
set "IS_MINIMIZED=1"
start "Clear Folders" /min %ComSpec% /C "%~f0" %*
exit /B
:ClearFolders
call :Clear_Folder "%SystemRoot%\TEMP"
if defined TEMP call :Clear_Folder "%TEMP%"
for /D %%k in (C:\Users\*) do if exist "%%k\AppData\Local\Temp" call :Clear_Folder "%%k\AppData\Local\Temp"
exit /B
:Clear_Folder
pushd "%~1"
if errorlevel 1 goto :EOF
rd /Q /S "%~1" 2>nul
popd
goto :EOF
See also my answer on How to delete files/subfolders in a specific directory at the command prompt in Windows? It explains why rd /Q /S "%~1" 2>nul
is enough to delete all subfolders and files in directory of which path is passed with argument 1 to the subroutine Clear_Folder
if that directory is really existing and pushd
successfully made it the current directory for the command process processing the batch file.
See also: Where does GOTO :EOF return to?
What happens after execution of first exit /B
depends on how this batch file was started and in which environment.
A double click on a batch file results in starting the Windows command processor cmd.exe
for processing the batch file with using implicit option /C
to close command process after execution of the batch file. In this case the first exit /B
results in closing initially opened console window as the Windows command process processing the batch file initially also closes.
Opening first a command prompt window results in starting cmd.exe
with using implicit option /K
to keep command process running after execution of a command line like executing this batch file. In this case the console window remains open after execution of first exit /B
as the command process keeps running for further command executions by the user.
The first exit /B
could be replaced by command exit
to always exit the command process independent on how cmd.exe
initially processing the batch file was started and independent on the calling hierarchy. So the usage of exit
is not advisable in case of this batch file is called from another batch file which does for example more hard disk cleanup operations.