System command

if command

Run a command conditionally in a batch script.

Availability: Microsoft Learn command reference spanning Windows client and Windows Server releases; some entries are legacy, role-specific, optional-feature or interactive subcommands.中文

Documented syntax

if [not] ERRORLEVEL <number> <command> [else <expression>]
if [not] <string1>==<string2> <command> [else <expression>]
if [not] exist <filename> <command> [else <expression>]
If command extensions are enabled, use the following syntax:
if [/i] <string1> <compareop> <string2> <command> [else <expression>]
if cmdextversion <number> <command> [else <expression>]
if defined <variable> <command> [else <expression>]

The linked Microsoft Learn article is the upstream authority. Availability may depend on Windows release, role, optional feature or interactive tool context.

Examples

Example usage for if.

if exist config.ini type config.ini

Parameters, options and clauses

Option / clauseDescription
notInvert the condition.
ERRORLEVEL <number>Test whether the last program exit code is at least the specified number.
exist <filename>Test whether a file exists.
<string1>==<string2>Compare two strings.
/iUse case-insensitive string comparison when command extensions are enabled.
defined <variable> / cmdextversion <number>Test a variable or the command-extensions version.
<command>Microsoft documents this argument or subcommand; check the linked reference for its required format and context.
<expression>Microsoft documents this argument or subcommand; check the linked reference for its required format and context.
<compareop>Microsoft documents this argument or subcommand; check the linked reference for its required format and context.
Safety note

Review a command and its target before running it. Commands that alter files, services, accounts, disks, permissions or databases may be difficult to reverse. Test in a safe environment and keep backups.

Official reference ↗Back to directory