How to wait for a process to terminate to execute another process in batch file
Solution 1:
Use start /w programname to wait for the end of programname
START /W notepad
ECHO Back from notepad
START /W wordpad
ECHO Back from wordpad
START /W notepad
Solution 2:
Try something like this...
@ECHO OFF
PSKILL NOTEPAD
START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"
:LOOP
PSLIST wordpad >nul 2>&1
IF ERRORLEVEL 1 (
GOTO CONTINUE
) ELSE (
ECHO Wordpad is still running
TIMEOUT /T 5
GOTO LOOP
)
:CONTINUE
NOTEPAD
I used PSLIST
and PSEXEC
, but you could also use TASKKILL
and TASKLIST
. The >nul 2>&1
is just there to hide all the output from PSLIST
. The SLEEP 5
line is not required, but is just there to restrict how often you check if WordPad is still running.
Solution 3:
This is an updated version of aphoria's Answer.
I Replaced PSLIST and PSEXEC with TASKKILL and TASKLIST`. As they seem to work better, I couldn't get PSLIST to run in Windows 7.
Also replaced Sleep with TIMEOUT.
This Was everything i needed to get the script running well, and all the additions was provided by the great guys who posted the comments.
Also if there is a delay before the .exe starts it might be worth inserting a Timeout before the :loop.
@ECHO OFF
TASKKILL NOTEPAD
START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"
:LOOP
tasklist | find /i "WORDPAD" >nul 2>&1
IF ERRORLEVEL 1 (
GOTO CONTINUE
) ELSE (
ECHO Wordpad is still running
Timeout /T 5 /Nobreak
GOTO LOOP
)
:CONTINUE
NOTEPAD
Solution 4:
I liked the "START /W" answer, though for my situation I found something even more basic. My processes were console applications. And in my ignorance I thought I would need something special in BAT syntax to make sure that the 1st one completed before the 2nd one started. However BAT appears to make a distinction between console apps and windows apps, and it executes them a little differently. The OP shows that window apps will get launched as an asynchronous call from BAT. But for console apps, that are invoked synchronously, inside the same command window as the BAT itself is running in.
For me it was actually better not to use "START /W", because everything could run inside one command window. The annoying thing about "START /W" is that it will spawn a new command window to execute your console application in.
Solution 5:
This works and is even simpler. If you remove ECHO-s, it will be even smaller:
REM
REM DEMO - how to launch several processes in parallel, and wait until all of them finish.
REM
@ECHO OFF
start "!The Title!" Echo Close me manually!
start "!The Title!" Echo Close me manually!
:waittofinish
echo At least one process is still running...
timeout /T 2 /nobreak >nul
tasklist.exe /fi "WINDOWTITLE eq !The Title!" | find ":" >nul
if errorlevel 1 goto waittofinish
echo Finished!
PAUSE