C:\_G\WWW\~ELISANET\INFO\tscmd158.html
<http://www.elisanet.fi/tsalmi/info/tscmd158.html>
Copyright © 2003- by Prof. Timo Salmi  
Last modified Thu 29-Nov-2018 13:39:40

 
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 /?

[Previous] [Next]

C:\_G\WWW\~ELISANET\INFO\tscmd158.html
C:\_G\WWW\~ELISANET\FTPCMD\TSALMI.CMD /tscmd158
http://www.elisanet.fi/tsalmi/info/tscmd158.html
file:///c:/_g/www/~elisanet/info/tscmd158.html