Steve
Steve

Reputation: 2073

Batch - Kill program if running, start it if it's not

I'm trying to make a toggle batch script for a process so that if it's running it gets killed and if it's not it is started. This is what I have:

tasklist /FI "IMAGENAME eq ProcessName.exe" 2>NUL | find /I /N "ProcessName.exe">NUL
set procopen = %ERRORLEVEL%
if "%procopen%"=="0" taskkill /im ProcessName.exe 
if NOT "%procopen%"=="0" start "" ProcessName.exe

But everytime I run it, after the first if statement I receive the error:

"1"=="0") was unexpected at this time.

I also feel like there's a more efficient way to write this, but I'm not exactly sure how. Any help is appreciated!

Upvotes: 1

Views: 4903

Answers (1)

rojo
rojo

Reputation: 24476

More efficient would be to use conditional execution.

tasklist | find /i "application.exe" >NUL && (
    taskkill /im "application.exe" /f
) || (
    start "" application.exe
)

I think the reason your script is failing is because you've got spaces surrounding your equal sign in your set procopen line. You're basically setting a variable named procopenspace=spacenumeral, with the spaces included in both the variable name and the value. In the set command, spaces are treated as literal space characters, rather than as token delimiters. Now if you had done set /a, it probably would've worked (as set /a is more tolerant of spacing). Or if you had left the spaces out and set "procopen=%ERRORLEVEL%", that probably would've worked too. Here's an example cmd console session to demonstrate:

C:\Users\me>set procopen = 0

C:\Users\me>set "res=%procopen%"

C:\Users\me>set res
res=%procopen%

C:\Users\me>set "res=%procopen %"

C:\Users\me>set res
res= 0

Upvotes: 5

Related Questions