lbr*_*tdy 7 command file batch-file choice errorlevel
我正在尝试创建一个批处理文件,根据正在执行的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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
但是,当它与检测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.
)
Run Code Online (Sandbox Code Playgroud)
如您所见,我甚至尝试在执行choice命令之前清除errorlevel var,但在执行choice命令后errorlevel保持为0.
有小费吗?谢谢!
dbe*_*ham 14
您遇到了一个经典问题 - 您正试图%errorlevel%在带括号的代码块中进行扩展.这种扩展形式发生在分析时,但整个IF构造一次被解析,因此值%errorlevel%不会改变.
解决方案很简单 - 延迟扩展.您需要SETLOCAL EnableDelayedExpansion在顶部,然后使用!errorlevel!.延迟扩展在执行时发生,因此您可以在括号内看到值的更改.
SET(SET /?)的帮助描述了FOR语句的问题和解决方案,但概念是相同的.
你还有其他选择.
您可以从代码的正文中IF移除代码,而不使用括号,并使用GOTO或CALL访问代码.然后你可以使用%errorlevel%.我不喜欢这个选项,因为CALL和GOTO相对较慢,并且降低了代码的优雅.
另一个选择是使用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
)
Run Code Online (Sandbox Code Playgroud)