I have come up with the following code which starts minimized, waits 5 seconds (for slow PC) deletes temp files after and should automatically close, but for some reason, automatic close is not working, .bat file stays minimized.
I tried using exit command but it has 0 effect because goto :EOF prevent it from execution, but if I will remove goto :EOF script won't delete temp files
if not DEFINED IS_MINIMIZED set IS_MINIMIZED=1 && start "" /min "%~dpnx0" %* && exit
PING localhost -n 5 >NUL
@echo off
setlocal
call :Clear_Folder %SystemRoot%\TEMP
pushd C:\Users
for /d %%k in (*) do if exist "%%k\AppData\Local\Temp" call :Clear_Folder "%%k\AppData\Local\Temp"
popd
endlocal
goto :EOF
:Clear_Folder
pushd "%~1"
for /d %%i in (*) do rd /s /q "%%i"
del /f /q *
popd
goto :EOF
exit
I'm looking forward to fix last step auto close, all other features work fine, the script starts minimized, it deletes temp files but after all of this it won't close itself and it stays minimized.
The reason your minimized script is not closing at the end is that you started the script directly, instead of as an argument to cmd.exe
with it's /C
option. When you run your script directly via Start
, cmd.exe
is run using the /K
option with your batch file as its argument. When the /K
option is used, as explained from running cmd /?
, the window remains open upon completion of the command. To close that window you need to explicitly exit
the cmd.exe
instance:
Here's my take on what you intended to do:
@If Not Defined IS_MINIMIZED Set "IS_MINIMIZED=1"&Start "" /Min "%~f0"&Exit
@Echo Off
Timeout 5 /NoBreak>NUL
Call :Clear_Folder "%SystemRoot%\TEMP"
For /D %%k In ("C:\Users\*")Do If Exist "%%k\AppData\Local\Temp\" Call :Clear_Folder "%%k\AppData\Local\Temp"
Exit
:Clear_Folder
PushD "%~1" 2>NUL||Exit /B
RD /S /Q "%~1" 2>NUL
PopD
GoTo :EOF
If there's no other content beneath this, you can also remove GoTo :EOF