批处理 - 如果正在运行则终止程序,如果没有则启动它

Ste*_*eve 1 windows process batch-file

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

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
Run Code Online (Sandbox Code Playgroud)

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

"1"=="0") was unexpected at this time.
Run Code Online (Sandbox Code Playgroud)

我也觉得有一种更有效的方法来写这个,但我不太确定如何写。任何帮助表示赞赏!

roj*_*ojo 5

更有效的是使用条件执行

tasklist | find /i "application.exe" >NUL && (
    taskkill /im "application.exe" /f
) || (
    start "" application.exe
)
Run Code Online (Sandbox Code Playgroud)

我认为你的脚本失败的原因是因为你的行中等号周围有空格set procopen。您基本上是在设置一个名为procopenspace=的变量spacenumeral,变量名称和值中都包含空格。在set命令中,空格被视为文字空格字符,而不是标记分隔符。现在,如果您这样做了set /a,它可能会起作用(因为set /a更能容忍间距)。或者,如果您省略了空格 和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