Windows – How to set a time-limit on a batch file

batch filewindows

I have a batch file that calls an external program that periodically hangs. What I would like to do is set a time limit on the batch file / CMD prompt such that it automatically closes after a certain period of time. One catch is that the external program that hangs may have one or more instances running at a given time, and I only want the batch file hitting its time limit to close the instance of the program triggered by the batch. How can I accomplish this? Ideally a solution would work on Windows XP, Vista, and 7.

Best Answer

REM start the program as quickly as possible to avoid other processes starting
tasklist > file1.txt & start notepad.exe & tasklist > file2.txt
REM Find the PID of the program we just started
for /f "tokens=2" %%a in ('fc file1.txt file2.txt^|find "notepad.exe"') do set PID=%%a
REM delay for 5 seconds
FOR /l %%a in (5,-1,1) do (Echo closing in %%as&ping -n 2 -w 1>NUL)
REM delete the program using it's PID
tskill %PID%

the ping -n 2 -w 1 will pause for almost exactly 1 second (the amount of time between 2 pings)
This works on XP, as choice is not included in XP

Related Question