<http://www.netikka.net/tsneti/info/tscmd146.htm>
Copyright © 2003-2010 by Prof. Timo Salmi  
Last modified Tue 6-Apr-2010 13:38:25

 
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.



146} Using delayed expansion for giving variable values as arguments

Consider the following snippet
  @echo off & setlocal enableextensions
  rem        0123456789
  set string=abcdefghij
  echo %string%
  echo %string:~2,4%
  endlocal & goto :EOF
As we well know the will result in the following where the substring starts from the position 1+2 (the string numbering starts from 0, see SET /?) and is four characters long.
  C:\_D\TEST>cmdfaq
  abcdefghij
  cdef

Next consider
  @echo off & setlocal enableextensions enabledelayedexpansion
  set i=2&set j=4
  echo %i% %j%
  rem        0123456789
  set string=abcdefghij
  echo %string%
  echo !string:~%i%,%j%!
  endlocal & goto :EOF

The output will be
  C:\_D\TEST>cmdfaq
  2 4
  abcdefghij
  cdef

An alternative solution, not needing explicit delayed extension, is
  @echo off & setlocal enableextensions disabledelayedexpansion
  set i=2&set j=4
  echo %i% %j%
  rem        0123456789
  set string=abcdefghij
  echo %string%
  call set s_=%%string:~%i%,%j%%%
  echo %s_%
  echo.
  endlocal & goto :EOF
The output will be exactly the same. The advantage of this alternative is that exclamation marks can appear as part of the string. For example
  @echo off & setlocal enableextensions disabledelayedexpansion
  set i=2&set j=4
  echo %i% %j%
  rem        0123456789
  set string=abc!efghij
  echo %string%
  call set s_=%%string:~%i%,%j%%%
  echo %s_%
  echo.
  endlocal & goto :EOF

will give
  C:\_D\TEST>cmdfaq
  2 4
  abc!efghij
  c!ef

Just for the sake of demonstration we also could as well use a subroutine
  @echo off & setlocal enableextensions disabledelayedexpansion
  set i=2&set j=4
  echo %i% %j%
  rem        0123456789
  set string=abc!efghij
  echo %string%
  call :EchoSubString "%string%" %i% %j%
  endlocal & goto :EOF
  ::
  :EchoSubString
  @echo off & setlocal enableextensions
  set s_=%~1
  call echo %%s_:~%2,%3%%
  endlocal & goto :EOF

Also this will give
  C:\_D\TEST>cmdfaq
  2 4
  abc!efghij
  c!ef

For more examples see e.g. items #40, #96, #132 and #141.