Batch IF 语句一次只处理一个动作吗?

Does Batch IF statement handles only one action at a time?

我是批处理脚本的新手,但根据我在 Bash 尝试理解事物的经验。我正在检查错误级别,如果 %ERRORLEVEL% == 0,我希望它回显一条消息,然后递增一个计数器变量,否则回显另一条消息并使用退出代码退出。

我做过的例子:

@echo off
SET counter=0

dir /a
SET RC=%ERRORLEVEL%
IF %RC% == 0 ECHO [INFO] - Command executed successfully. SET /A counter=counter+1 ELSE ECHO [ERROR] - Something went wrong here EXIT /B 99

上面的例子没有像我预期的那样工作。 IF-ELSE 语句在一行上,我得到的输出是

Command executed successfully. SET /A counter=counter+1

当我在 () 中包含 echo 和 set 命令时,它会抱怨

(set was unexpected at this time

那么,我怎样才能 ON TRUE 回显一条消息并将计数器加 1;如果错误,则使用特定的 %ERRORLEVEL% 代码退出脚本?

您可以处理各种操作,将这些操作放在代码块中 ()

您可以使用条件 &&|| 运算符:

dir /a && (
    echo success
    SET /A counter+=1
    ) || echo failed

或:

IF %RC%==0 (
   ECHO [INFO] - Command executed successfully. 
   SET /A counter=counter+1
   ) ELSE (
   ECHO [ERROR] - Something went wrong here 
   EXIT /B 9
)

我相信这就是您要找的。

@echo off
SET counter=0

dir /a
SET RC=%ERRORLEVEL%
IF %RC% == 0 (ECHO [INFO] - Command executed successfully. & (SET /A counter=counter+1)) ELSE (ECHO [ERROR] - Something went wrong here & (EXIT /B 99))

Counter,执行成功则值为1。此外,使用 dir /a 需要 /a 之后的属性,例如隐藏文件的 /a:h。做dir /?以获得更多属性。