実行中の Windows のバージョンに基づいて、異なる「選択」コマンドを実行するバッチ ファイルを作成しようとしています。Windows 7 と Windows XP では、choice コマンドの構文が異なります。
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 OS のバージョンを検出するコマンドと組み合わせると、Windows XP と Windows 7 の両方のコード ブロックで、choice コマンドの後、AN の前に errorlevel が 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.
)
ご覧のとおり、choice コマンドを実行する前に errorlevel 変数をクリアしようとしましたが、choice コマンドの実行後も errorlevel は 0 のままです。
任意のヒント?ありがとう!