简体   繁体   中英

Get out of loop if more than one minute Windows Batch file

I am trying to delete a folder on Windows server if a certain condition is met. If it is not met, then a wait for 10 seconds and loop around, check for the condition again. I also need to make sure that I am not in the loop forever. (Check if I am in the loop for more than 60 seconds, then get out of the loop). The batch file looks something like this:

C:\postgresql\uninstall-postgresql.exe --mode unattended
set TIMESTAMP1=%TIME%
:deleteFolder
tasklist /V |findstr /i "_uninstall*" >nul
if %errorlevel% == 0 (timeout /T /10 >nul
set TIMESTAMP2=%TIME%
**REM I want to make sure that we get out of this loop if the diff b/w TIMESTAMP2 
AND TIMESTAMP1 IS MORE THEN 60 SECONDS**
goto deleteFolder 
) ELSE (
if exists C:\postgresql RD /Q /S C:\postgresql)

Command 1
Command 2
Command 3

So, I am trying to uninstall Postgresql from a windows server, making sure that the uninstall is complete by checking the tasklist and then delete the basedir (C:\\postgresql). If the uninstall process is still running, then wait for 10 seconds and check the tasklist again. I just want to make sure that I am not stuck in the loop forever.

Thanks in advance

The simpler method would be to utitlise a count to break the loop

@Echo off & Set Count=0
 C:\postgresql\uninstall-postgresql.exe --mode unattended

:deleteFolder
If "%Count%"=="6" Goto :Failed
tasklist /V |%__AppDir_%findstr.exe /lic:"_uninstall" >nul 2> Nul && (Timeout /T 10 /Nobreak > Nul & <Nul Set /P "=." & Set /A "count+=1" & Goto :deleteFolder) || Goto :Post
:Post
if exist C:\postgresql (
 RD /Q /S C:\postgresql && Echo/Task Completed
) Else Echo/C:\postgresql Absent
Goto :Eof
:Failed
 Echo/Task failed to complete in the allocated time
Goto :Eof

I would however suggest a more robust approach on your part to identifying the task

Using timestamps and calculating time difference :

@echo off
setlocal EnableDelayedExpansion

C:\postgresql\uninstall-postgresql.exe --mode unattended

set "startTime=%time: =0%"
set "endTime="

:deleteFolder
tasklist /V |findstr /i "_uninstall*" >nul
if %errorlevel% == 0 (
    goto waitAndDeleteFolder
) else (
    goto cleanup
)

:waitAndDeleteFolder
timeout /T 10
set "endTime=%time: =0%"
set "end=!endTime:%time:~8,1%=%%100)*100+1!"  &  set "start=!startTime:%time:~8,1%=%%100)*100+1!"
set /A "elap=((((10!end:%time:~2,1%=%%100)*60+1!%%100)-((((10!start:%time:~2,1%=%%100)*60+1!%%100), elap-=(elap>>31)*24*60*60*100"
if !elap! gtr 6000 goto done
goto deleteFolder

:cleanup
if exist "C:\postgresql" RD /Q /S "C:\postgresql"
goto done

:done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM