9

実行中の 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 のままです。

任意のヒント?ありがとう!

4

1 に答える 1

17

古典的な問題に出くわしました-%errorlevel%括弧で囲まれたコードブロック内で展開しようとしています。この形式の展開は解析時に発生しますが、IF コンストラクト全体が一度に解析されるため、 の値は%errorlevel%変化しません。

解決策は簡単です - 拡張を遅らせます。SETLOCAL EnableDelayedExpansion上部に必要な場合は、!errorlevel!代わりに使用します。遅延展開は実行時に発生するため、括弧内の値の変化を確認できます。

SET ( SET /?) のヘルプに FOR 文に関する問題と解決策が記載されていますが、考え方は同じです。

他のオプションがあります。

の本体内からコードのIFラベル付きセクションに括弧なしでコードを移動し、GOTOまたはCALLを使用してコードにアクセスできます。その後、使用できます%errorlevel%CALLGOTOは比較的遅く、コードが洗練されていないため、このオプションは好きではありません。

別のオプションは、IF ERRORLEVEL Nの代わりに使用することですIF !ERRORLEVEL!==N。( を参照IF /?) IF ERRORLEVEL Nerrorlevel が >= 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
)
于 2011-12-23T13:48:16.317 に答える