批处理 - 通过选择命令设置变量

Batch - Set variable through choice command

我正在编写一个小批处理脚本,其中包含类似于下面代码块的部分...可以轻描淡写地说这让我感到困惑,以至于我的头脑已经完全麻木了。 .. 为什么在盖亚的绿色背面不起作用...?

@echo off

set log=0
choice /m "Choose "
if errorlevel 2 set log=N
if errorlevel 1 set log=Y

echo %log%
pause

if "%log%"=="N" (
echo hello
)


if "%log%"=="Y" (
echo goodbye
)
pause
if errorlevel 2 set log=N
if errorlevel 1 set log=Y

翻译:

如果错误级别为 2 或大于 2,则设置 log=N
如果错误级别为 1 或大于 1,则设置 log=Y

so - 反转行,因为如果 errorlevel 为 2,它既是 2 or greater than 2(所以设置 N)然后是 1 or greater than 1(所以设置 Y

Windows(和旧的 DOS)中的一个奇怪之处是,如果你设置 "if errorlevel ...",它实际上意味着 "if the errorlevel is greater than this number..." 所以如果你说 "if errorlevel 1" 你的意思是 "if errorlevel > 1".

试试这个:

if errorlevel 1 if not errorlevel 2 (do stuff)

if errorlevel 2 if not errorlevel 3 (do other stuff)

或者,您可以使用临时变量 %ERRORLEVEL%...