if

在批次程式執行條件式處理。

語法

if [not] ERRORLEVEL <number> <command> [else <expression>]
if [not] <string1>==<string2> <command> [else <expression>]
if [not] exist <filename> <command> [else <expression>]

如果已啟用命令延伸模組,請使用下列語法:

if [/i] <string1> <compareop> <string2> <command> [else <expression>]
if cmdextversion <number> <command> [else <expression>]
if defined <variable> <command> [else <expression>]

參數

參數 描述
not 指定只有在條件為 false 時,才應執行命令。
errorlevel <number> 只有在 Cmd.exe 執行的上一個程式傳回等於或大於 number 的結束代碼時,才會指定 true 條件。
<command> 指定只有在符合上述條件時,才應執行命令。
<string1>==<string2> 只有在 string1 和 string2 相同時,才會指定 true 條件。 這些值可以是常值字串或批次變數 (例如 %1)。 您不需要使用引號括住常值字串。
exist <filename> 如果指定的檔案名稱存在,則會指定 true 條件。
<compareop> 指定由三個字母組成的比較運算子,包括:
  • EQU - 等於
  • NEQ - 不等於
  • LSS - 小於
  • LEQ - 小於或等於
  • GTR - 大於
  • GEQ - 大於或等於
/i 強制規定字串比較會忽略大小寫。 您可以在 ifstring1==string2 形式中使用 /i。 這些比較皆為一般比較,如果當中的 string1 和 string2 都是僅由數字組成,字串就會轉換為數字,並執行數值比較。
cmdextversion <number> 只有在與 Cmd.exe 之命令延伸模組功能相關的內部版本數字等於或大於指定的數字時,才會指定 true 條件。 第一個版本為 1。 當命令延伸模組新增大量的增強功能時,就會逐一遞增。 當命令延伸模組停用時 (命令延伸模組會預設啟用),cmdextversion 條件永遠不會為 true。
defined <variable> 如果已定義 variable,則會指定 true 條件。
<expression> 指定將命令列和任何參數傳遞至 else 子句中的命令。
/? 在命令提示字元顯示說明。

備註

  • 如果 if 子句中指定的條件為 true,就會執行該條件後方的命令。如果條件為 false,則 if 子句會遭到忽略,而命令則會執行在 else 子句中指定的任何命令。

  • 當程式停止運作時,就會傳回結束代碼。 若要使用結束代碼做為條件,請使用 errorlevel 參數。

  • 如果使用 defined,就會將下列三個變數新增至環境:%errorlevel%、%cmdcmdline% 和 %cmdextversion%

    • %errorlevel%:展開為 ERRORLEVEL 環境變數目前值的字串表示。 這個變數會假設目前還不存在名為 ERRORLEVEL 的現有環境變數。 若已存在,您將改為取得該 ERRORLEVEL 值。

    • %cmdcmdline%:展開為在 Cmd.exe 進行任何處理作業之前,傳遞至 Cmd.exe 的原始命令列。 這會假設目前還不存在名為 CMDCMDLINE 的現有環境變數。 若已存在,您將改為取得該 CMDCMDLINE 值。

    • %cmdextversion%:展開為 cmdextversion 目前值的字串表現。 這會假設目前還不存在名為 CMDEXTVERSION 的現有環境變數。 若已存在,您將改為取得該 CMDEXTVERSION 值。

  • 您必須在相同命令列中的 if 後方使用 else 子句。

範例

若要顯示「Cannot find data file if the file Product.dat cannot be found」(如果找不到 Product.dat,便無法找到檔案資料) 訊息,請輸入:

if not exist product.dat echo Cannot find data file

若要將磁碟機 A 中的磁碟格式化,並在格式化過程發生錯誤時顯示錯誤訊息,請在批次檔案中輸入下列程式碼:

:begin
@echo off
format a: /s
if not errorlevel 1 goto end
echo An error occurred during formatting.
:end
echo End of batch program.

若要從目前的目錄中刪除檔案 Product.dat,或在找不到 Product.dat 時顯示訊息,請在批次檔案中輸入下列程式碼:

IF EXIST Product.dat (
del Product.dat
) ELSE (
echo The Product.dat file is missing.
)

注意

這些程式碼可合併在同一行,如下列所示:

IF EXIST Product.dat (del Product.dat) ELSE (echo The Product.dat file is missing.)

若要在執行批次檔案後回應 ERRORLEVEL 環境變數值,請在批次檔案中輸入下列程式碼:

goto answer%errorlevel%
:answer1
echo The program returned error level 1
goto end
:answer0
echo The program returned error level 0
goto end
:end
echo Done!

若要在 ERRORLEVEL 環境變數值小於或等於 1 時前往 okay 標籤,請輸入:

if %errorlevel% LEQ 1 goto okay