共用方式為


if

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

Syntax

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>]

Parameters

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

Remarks

  • 如果 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 子句。

Examples

如果 找不到檔案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.
)

Note

這些行可以合併成單行,如下所示:

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!

若要移至OK標籤,如果 ERRORLEVEL 環境變數的值小於或等於 1,請輸入:

if %errorlevel% LEQ 1 goto okay