批处理命令中的嵌套 If-Else

Nested If-Else in batch command

我正在尝试检查是否存在两项服务。如果其中一个不存在,它应该打印 "No" 否则打印 "Yes"。我试过的是:

@echo off
set service1=present_service
set service2=not_present

sc query %service1% | find "does not exist" >nul
if %ERRORLEVEL% EQU 1 (
    sc query %service2% | find "does not exist" >nul
    if %ERRORLEVEL% EQU 1 (
      echo Yes
    ) else (
      echo No
    )    
) else (
echo No
)

如果我检查单个,它工作正常。这里可能 %ERRORLEVEL% 在第二种情况下没有改变它的值。即使 service2 不存在,它也会打印 Yes。我可以得到任何帮助吗?

试试这个;

@echo off
setlocal EnableDelayedExpansion
set service1=present_service
set service2=not_present

sc query %service1% | find "does not exist" >nul
if %ERRORLEVEL% EQU 1 (
    sc query !service2! | find "does not exist" >nul
    if !ERRORLEVEL! EQU 1 (
      echo Yes
    ) else (
      echo No
    )    
) else (
echo No
)

这是 delayed expansion

的问题

有几种方法可以 assemble 和 "AND" 查询多个条件;这是一个非常简单的方法:

@echo off
setlocal
set service1=present_service
set service2=not_present

sc query %service1% | find "does not exist" >nul
set "bothServices=%ERRORLEVEL%"
sc query %service2% | find "does not exist" >nul
set "bothServices=%bothServices%%ERRORLEVEL%"

if %bothServices% EQU 11 (
   echo Yes
) else (
   echo No
)    

此方法还允许测试 2 个以上的条件,而不会使代码过于复杂...