【问题标题】:Batch file 'choice' command's errorlevel returns 0批处理文件“选择”命令的错误级别返回 0
【发布时间】:2012-01-26 11:47:33
【问题描述】:

我正在尝试创建一个批处理文件,该批处理文件根据正在执行的 Windows 版本执行不同的“选择”命令。选择命令的语法在 Windows 7 和 Windows XP 之间有所不同。

Choice 命令为 Y 返回 1,为 N 返回 2。以下命令返回正确的错误级别:

Windows 7:

choice /t 5 /d Y /m "Do you want to automatically shutdown the computer afterwards "
echo %errorlevel%
if '%errorlevel%'=='1' set Shutdown=T
if '%errorlevel%'=='2' set Shutdown=F

Windows XP:

choice /t:Y,5 "Do you want to automatically shutdown the computer afterwards "
echo %ERRORLEVEL%
if '%ERRORLEVEL%'=='1' set Shutdown=T
if '%ERRORLEVEL%'=='2' set Shutdown=F

但是,当它与检测 Windows 操作系统版本的命令结合使用时,errorlevel 在我的 Windows XP 和 Windows 7 代码块中的选择命令之后的 AN 之前返回 0。

REM Windows XP
ver | findstr /i "5\.1\." > nul
if '%errorlevel%'=='0' (
set errorlevel=''
echo %errorlevel%
choice /t:Y,5 "Do you want to automatically shutdown the computer afterwards "
echo %ERRORLEVEL%
if '%ERRORLEVEL%'=='1' set Shutdown=T
if '%ERRORLEVEL%'=='2' set Shutdown=F
echo.
)

REM Windows 7
ver | findstr /i "6\.1\." > nul
if '%errorlevel%'=='0' (
set errorlevel=''
echo %errorlevel%
choice /t 5 /d Y /m "Do you want to automatically shutdown the computer afterwards "
echo %errorlevel%
if '%errorlevel%'=='1' set Shutdown=T
if '%errorlevel%'=='2' set Shutdown=F
echo.
)

如你所见,我什至尝试在执行选择命令之前清除errorlevel var,但在执行选择命令后errorlevel 仍然为0。

有什么建议吗? 谢谢!

【问题讨论】:

    标签: file batch-file command choice errorlevel


    【解决方案1】:

    您遇到了一个经典问题 - 您正试图在带括号的代码块内扩展 %errorlevel%。这种形式的扩展发生在解析时,但整个 IF 构造被一次解析,所以%errorlevel% 的值不会改变。

    解决方案很简单 - 延迟扩展。您需要在顶部使用SETLOCAL EnableDelayedExpansion,然后改用!errorlevel!。延迟扩展发生在执行时,因此您可以看到括号内值的更改。

    SET (SET /?) 的帮助描述了与 FOR 语句有关的问题和解决方案,但概念是相同的。

    您还有其他选择。

    您可以将代码从IF 的正文中移动到没有括号的代码段,并使用GOTOCALL 访问代码。然后你可以使用%errorlevel%。我不喜欢这个选项,因为CALLGOTO 比较慢,而且代码也不太优雅。

    另一种选择是使用IF ERRORLEVEL N 而不是IF !ERRORLEVEL!==N。 (参见IF /?)因为IF ERRORLEVEL N 测试errorlevel 是否>= N,所以您需要按降序执行测试。

    REM Windows XP
    ver | findstr /i "5\.1\." > nul
    if '%errorlevel%'=='0' (
      choice /t:Y,5 "Do you want to automatically shutdown the computer afterwards "
      if ERRORLEVEL 2 set Shutdown=F
      if ERRORLEVEL 1 set Shutdown=T
    )
    

    【讨论】:

      猜你喜欢
      • 2021-02-27
      • 2015-01-21
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      • 1970-01-01
      相关资源
      最近更新 更多