否则条件总是执行...我错在哪里?

否则条件总是执行...我错在哪里?

我正在尝试让这个东西工作,但出于某种原因,即使我认为它是正确的,它似乎并没有遵守 else 语句。结果,就像没有 else 一样,它只是执行所有代码行。目的是检查是否有东西正在运行。如果是,那么它应该显示一条消息并保持命令窗口打开,以便人们可以看到需要做什么来修复它,然后当按下一个键时,命令窗口会关闭。如果它没有运行,它会为他们启动它并关闭命令窗口,这样人们就看不到它了。

以下是显示正在发生的事情的输出(删除了空行以节省空间):

C:\Users\me2\Desktop>QPROCESS "Pulse.exe" 1>NUL No Process exists for pulse.exe
C:\Users\me2\Desktop>REM 0 means that it's running (ProcessFound) and 1 mean s it's not (ProcessNotFound)
C:\Users\me2\Desktop>REM cmd /k IF (1 EQU 0 goto ProcessFound) ELSE (goto Pr ocessNotFound)
C:\Users\me2\Desktop>REM cmd /k IF 1 NEQ 0 (
C:\Users\me2\Desktop>cmd /k IF ERRORLEVEL 1 (
C:\Users\me2\Desktop>echo In ProcessNotFound In ProcessNotFound
C:\Users\me2\Desktop>REM cd C:\Program Files (x86)\Common Files\Pulse Secure \JamUI\
C:\Users\me2\Desktop>REM start "" Pulse.exe -tray
C:\Users\me2\Desktop>echo In ProcessFound In ProcessFound
C:\Users\me27\Desktop>REM cls 0
Pulse Secure is running. It must be stopped by right clicking on the icon and clicking Exit.
Press any key to continue . . .

代码如下:

QPROCESS "Pulse.exe">NUL
REM 0 means that it's running (ProcessFound) and 1 means it's not (ProcessNotFound)
REM cmd /k IF (%ERRORLEVEL% EQU 0 goto ProcessFound) ELSE (goto ProcessNotFound)
REM cmd /k IF %ERRORLEVEL% NEQ 0 (
cmd /k IF ERRORLEVEL 1 (
     :ProcessNotFound
     echo In ProcessNotFound
     REM cd C:\Program Files (x86)\Common Files\Pulse Secure\JamUI\
     REM start "" Pulse.exe -tray
) ELSE (
     :ProcessFound
     echo In ProcessFound
 REM    cls
     @echo off
     echo %ERRORLEVEL%
     ECHO.
     ECHO.
     ECHO Pulse Secure is running.
     ECHO It must be stopped by right clicking on the icon and clicking Exit.
     ECHO.
     ECHO.
     PAUSE
     )
REM IF %ERRORLEVEL% EQU 0 ECHO "Pulse Secure is running.  It must be stopped by right clicking on the icon and clicking Exit."

答案1

  • cmd /k将在同一个窗口中生成一个新的 cmd.exe 实例。
  • 这个新的 cmd.exe 中的错误级别指的是 cmd.exe 本身的启动,这显然曾是成功,因此错误级别为 0
  • 只需删除所有不必要的cmd /k
  • 您可能还会检查%errorlevel%,但这并不意味着if errorlevel x or greater您的语法的作用。

在不知道你的 QPROCESS 的情况下,你可以在失败||或成功时使用条件执行&& ,参见https://ss64.com/nt/syntax-conditional.html

QPROCESS "Pulse.exe" >NUL 2>&1 || (
    echo In ProcessNotFound
    REM cd C:\Program Files (x86)\Common Files\Pulse Secure\JamUI\
    REM start "" Pulse.exe -tray
) && (
    echo In ProcessFound
    echo %ERRORLEVEL%
    ECHO.
    ECHO Pulse Secure is running.
    ECHO It must be stopped by right clicking on the icon and clicking Exit.
    ECHO.
    PAUSE
)

相关内容