<http://www.netikka.net/tsneti/info/tscmd158.htm>
Copyright © 2003-2010 by Prof. Timo Salmi  
Last modified Sun 9-May-2010 18:16:38

 
Assorted NT/2000/XP/.. CMD.EXE Script Tricks
From the html version of the tscmd.zip 1cmdfaq.txt file
To the Description and the Index
 

This page is edited from the 1cmdfaq.txt faq-file contained in my tscmd.zip command line interface (CLI) collection. That zipped file has much additional material, including a number of detached .cmd script files. It is recommended that you also get the zipped version as a companion.

Please see "The Description and the Index page" for the conditions of usage and other such information.



158} Why won't the statements within my if condition work properly?

There are several examples throughout the 1CMDFAQ.TXT FAQ about for loops which require delayed expansion. The need for delayed expansion is, however, not limited to for-loops. Below is an artificial example reminding the reader that the operations within an if statement have the same feature:
  @echo off & setlocal enableextensions
  set par1=%1
  if "%par1%"=="a" (
    set par2=%2
    echo %par2%
    )
  endlocal & goto :EOF

The output will be
  C:\_D\TEST>cmdfaq a b c d
  ECHO is off.

However, written appropriately
  @echo off & setlocal enableextensions enabledelayedexpansion
  set par1=%1
  if "%par1%"=="a" (
    set par2=%2
    echo !par2!
    )
  endlocal & goto :EOF

The output will be what one rather would want:
  C:\_D\TEST>cmdfaq a b c d
  b

The latter could, of course, also be written as
  @echo off & setlocal enableextensions disabledelayedexpansion
  set par1=%1
  if not "%par1%"=="a" goto next1
    set par2=%2
    echo %par2%
  :next1
  endlocal & goto :EOF

Also see item38.

Next, consider a practical example which involves multiple related aspects including for-loops, if-statements and testing errorlevels. The task is to test the integrity of a set of .zip files. The following code will tell whether they all pass, or if any number of them includes errors.
  @echo off & setlocal enableextensions enabledelayedexpansion
  set unzipProg=C:\_F\TOOLS\PKUNZIP.EXE
  set error_=
  for %%f in ("C:\_E\TSZIP\*.ZIP") do (
    "%unzipProg%" -t "%%f">nul
    if !errorlevel! GTR 0 set error_=true)
  if defined error_ (
    echo Error^(s^) in at least one of the browsed .zip files
    ) else (
    echo No errors in the browsed .zip files)
  endlocal & goto :EOF

References/Comments:
  Environment variable expansion occurs when the command is read
  SET /?