Windows Commands: Conditionally perform a command


IF-Windows Command

IF

Conditionally perform a command.

File syntax
IF [NOT] EXIST filename command IF [NOT] EXIST filename (command) ELSE (command) String syntax
IF [/I] [NOT] item1==item2 command IF [/I] item1 compare-op item2 command IF [/I] item1 compare-op item2 (command) ELSE (command) Error Check Syntax IF [NOT] DEFINED variable command IF [NOT] ERRORLEVEL number command IF CMDEXTVERSION number command key item : May be a text string or an environment variable a variable may be modified using either
Search syntax> command : The command to perform NOT : perform the command if the condition is false. == : perform the command if the two strings are equal. /I : Do a case Insensitive string comparison. compare-op : may be one of EQU : equal NEQ : not equal LSS : less than < LEQ : less than or equal <= GTR : greater than > GEQ : greater than or equal >= This 3 digit syntax is necessary because the > and < are recognised as redirection symbols

IF EXIST filename will return true if the file exists (this is not case sensitive).

IF ERRORLEVEL statements should be read as IF Errorlevel > number
i.e.
IF ERRORLEVEL 1 will return TRUE for an errorlevel of 2

Normal completion of a command will return ERRORLEVEL=0

Any test made using the compare-op syntax will always be a "string" comparison,
so when comparing numbers note that "026" > "26"

IF NULL

To test for the existence of a command line paramater - use empty brackets like this

IF [%1] ==[] ECHO Value Missing
or
IF [%1] EQU [] ECHO Value Missing

In the case of a variable that may be NULL - a null variable will remove the variable definition altogether, so testing for NULLs becomes easy:

IF NOT DEFINED _example ECHO Value Missing

IF DEFINED will return true if the variable contains any value (even if the value is just a space)

Test the existence of files and folders

IF EXIST name - will detect the existence of a file or a folder - the script empty.cmd will show if the folder is empty or not.

BRACKETS

The use of brackets is only required if the command is run over several lines e.g.

IF EXIST filename (
del filename
) ELSE (
echo The file was not found.
)

The IF statement does not use any great intelligence when evaluating Brackets, so for example the command below will fail:

IF EXIST MyFile.txt (ECHO Some(more)Potatoes)

This version will work:

IF EXIST MyFile.txt (ECHO Some[more]Potatoes)

Testing Numeric values

Do not use brackets or quotes if you are comparing numeric values
e.g.
IF (2) GEQ (15) echo "bigger"
or
IF "2" GEQ "15" echo "bigger"
Will perform a character comparison and will echo "bigger"
however the command
IF 2 GEQ 15 echo "bigger"
Will perform a numeric comparison and works as expected - notice that this is opposite to the SET /a command where quotes are required.

CMDEXTVERSION

If Command Extensions are disabled CMDEXTVERSION will return FALSE otherwise it will return "1".
If command extensions are significantly enhanced in a future version of Windows then CMDEXTVERSION will be incremented.

Examples:

IF EXIST C:\install.log (echo Installation complete) ELSE (echo The Installation failed)

IF DEFINED _department ECHO Got the department variable

IF DEFINED _commission SET /A _salary=%_salary% + %_commission%

IF CMDEXTVERSION 1 GOTO :start_process

IF ERRORLEVEL EQU 0 goto :okay

:: Capture a specific errorlevel like this
FOR %%G in (0 1 2 3 4 5 6 7 8 9) DO if errorlevel==%%G set _err=%%G
IF [%_err%]==[2] echo Errorlevel is 2

:: Wildcards are not supported by IF but you can spoof the same thing using SET:
:: This won't Work
IF %COMPUTERNAME%==ABZ* GOTO :s_matched

:: This will work
SET _part_name=%COMPUTERNAME:~0,3%
IF NOT %_part_name%==ABZ GOTO :s_matched

Notes:

When piping commands, the expression is evaluated from left to right, so

IF... | ... is equivalent to (IF ... ) | ...

you can use the explicit syntax IF (... | ...)

Testing ERRORLEVEL correctly

It is possible to create a string variable called %ERRORLEVEL%
if present such a variable will prevent the real ERRORLEVEL from being read.
Both ECHO %errorlevel% and IF %errorlevel% will respond to a string variable %ERRORLEVEL% in preference to a real ERRORLEVEL.

To test for this problem use SET errorlevel, or IF DEFINED ERRORLEVEL

If you want to deliberately raise an ERRORLEVEL in a batch script use the command "COLOR 00" or simply SET MyError=YES

If Command Extensions are disabled IF will only support direct comparisons: IF ==, IF EXISTS, IF ERRORLEVEL

Other Windows 98, Windows XP Commands:
addusers , arp , assoc , associate , at , attrib , browstat , cacls , call , cd , change , chkdsk , chkntfs , choice , cipher , cleanmgr , clip , cmd , color , comp , con2prt , copy , date , defrag , del , delprof , dir , diruse , diskcomp , diskcopy , doskey , dsadd , dsmod , echo , endlocal , exit , expand , expand , fc , fdisk , find , findstr , for , forfiles , format , fsutil , ftp , ftype , global , goto , help , hfnetchk , if , ifmember , ipconfig , kill , label , ldifde , local , logevent , logoff , logtime , mapisend , md , mem , mode , monitor , more , mountvol , move , moveuser , msg , msiexec , msinfo32 , mstsc , munge , mv , nbtstat , net , netdom , netsh , netstat , netsvc , now , nslookup , ntbackup , ntrights , path , pathping , pause , perms , ping , popd , portqry , print , prncnfg , prnmngr , prompt , pushd , qgrep , rasdial , rasphone , rd , rdisk , recover , reg , regedit , regsvr32 , rem , ren , replace , rmtshare , robocopy , route , runas , rundll32 , sc , schtasks , sclist , scriptit , set , setlocal , setx , share , shift , shortcut , showgrps , showmbrs , shutdown , sleep , soon , sort , start , su , subinacl , subst , tasklist , time , timeout , title , touch , tracert , type , ver , verify , vol , where , whoami , windiff , winmsd , winmsdp , wmic , xcacls , xcopy ,
Live2Support.com :
Product - Benefits - Features - How Does it Works - Pricing - SSL Certificates - Signup - Contactus - Login - Submit Resources