Using a second Batch is the way to go as the other answers have suggested.
But searching through your entire verbose tasklist with "tasklist /v" is a very slow and ineffective process. Takes multiple seconds on my machine.
You can manipuate the tasklist command output to only show your batch (which is way more effective) and use that output directly like this without needing a pipe:
:START
for /f "tokens=1 delims=," %%G in ('tasklist /FI "WINDOWTITLE EQ TITLE_OF_ORIGINAL_BATCH" /FO CSV /NH') do (
if not %%G=="cmd.exe" (
REM EXECUTE COMMANDS WHEN THE WINDOW IS CLOSED
exit
)
)
ping 127.0.0.1>nul
goto START
Explanation:
First we fetch a single line of csv-style tasklist output which would either look like this if it finds your batch:
"cmd.exe","8172","Console","1","4.228 K"
or like this if there's no such window title in the tasklist:
"INFORMATION: blablabla..."
We throw this into that FOR /F loop that runs only once and only picks the first token:
"cmd.exe" or "INFORMATION: blablabla...".
Now "cmd.exe"/"INFO..." is in variable %G that can be used in an IF statement to get the definitive answer wether the other task is alive or dead.
Bonus fact: You can use a single .bat file to launch both scripts simultanously like this:
@echo off
if "%1" == "" start "" "%~f0" FLAG && goto actual_script
title EXIT_CHECK
:START
for /f "tokens=1 delims=," %%G in ('tasklist /FI "WINDOWTITLE EQ ORIGINAL_BATCH" /FO CSV /NH') do (
if not %%G=="cmd.exe" (
REM COMMANDS TO EXECUTE HERE WHEN THE MAIN WINDOW IS CLOSED
exit
)
)
ping -n 2 127.0.0.1>nul
goto START
:actual_script
title ORIGINAL_BATCH
:loop
REM SCRIPT GOES HERE
ping -n 2 127.0.0.1>nul
goto loop