Search code examples
batch-filetimertaskkill

Taskkill and timer in batch


I currently have this batch script:

start udp%1.exe
timeout /t %2
taskkill /f /im "udp%1.exe"

This works great and kills the program after a selected amount of time, however if I was to manually close udp%1.exe and start another one with the same ID the timer from the other batch script is still running and will kill the next launched. I'm not entirely sure if I can check if the process is still running in batch? and if so to close the timer so it doesn't kill others with the same ID?


Solution

  • Try this code:

    @echo off
    start "udp%1.exe"
    timeout /t %2
    
    tasklist /FI "IMAGENAME eq udp%1.exe" 2>NUL | find /I /N "udp%1.exe">NUL
    if "%ERRORLEVEL%"=="0" goto yes
    goto no
    
    :yes
    taskkill /f /im "udp%1.exe"
    exit
    
    :no
    exit
    

    It waits the selected amount of time and if the program is running, it closes it, and if the program is not running, it exits. If you wan't to detect if the program is closed while the timer is still running, you might want to look into vbs scripts. :)