批处理 - 如果 运行 则终止程序,如果不是则启动它

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

我正在尝试为一个进程制作一个切换批处理脚本,这样如果它 运行ning 它就会被杀死,如果不是它就会启动。这是我的:

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

但每次我 运行 它,在第一个 if 语句之后我收到错误:

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

我也觉得有一种更有效的方式来写这个,但我不确定如何写。感谢您的帮助!

更有效的方法是使用 conditional execution

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

我认为您的脚本失败的原因是您在 set procopen 行的等号周围有 spaces。您基本上是在设置一个名为 procopenspace=spacenumeral 的变量, space 包含在变量名称和值中。在 set 命令中,space 被视为文字 space 字符,而不是标记定界符。现在,如果您已完成 set /a,它可能会起作用(因为 set /a 对间距的容忍度更高)。或者,如果您将 space 和 set "procopen=%ERRORLEVEL%" 排除在外,那可能也会奏效。这是一个用于演示的示例 cmd 控制台会话:

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