Search code examples
batch-filewindows-server-2008-r2tasklist

Batch File to Check for Running Program and Start if not Running is not working


I have been trying to get this batch file to work but keep running into issues. I think I am close but need help getting this working. When the script runs I get Find: Parameter format not correct.

I am running this on a Windows Server 2008 R2 Standard.

@echo off 


tasklist /FI "IMAGENAME eq program.exe" | find /i “program.exe" 


IF ERRORLEVEL 2 GOTO NEXTPROGRAM

IF ERRORLEVEL 1 GOTO LAUNCHPROGRAM


:NEXTPROGRAM

goto SMADMIN



:LAUNCHPROGRAM

start "" "C:\path\to\program.exe"

goto SMADMIN


:SMADMIN

tasklist /FI "IMAGENAME eq program1.exe" | find /i “program1.exe" 


IF ERRORLEVEL 2 GOTO NEXTPROGRAM2

IF ERRORLEVEL 1 GOTO LAUNCHPROGRAM2


:NEXTPROGRAM2

goto COMPLETE



:LAUNCHPROGRAM2

start "" "C:\path\to\program1.exe"

goto COMPLETE

Solution

  • You can check whether the exe is running this way:

    SET running=0
    FOR /f "tokens=*" %%A IN ('tasklist^ /v^| findstr /i /c:"program.exe"') DO SET running=1
    IF %running%=1 GOTO NEXTPROGRAM
    IF %running%=0 GOTO LAUNCHPROGRAM
    

    Afterwards you just have to check if the %ProgramRunning% is set to 1.

    Don't forget to reset the %running% flag back to 0 before reusing it.