Skip navigation

JSI Tip 4860. The CALL command will expand nested environment variables


If your batch script needs to determine if a string is a sub-set of a larger string,
the easiest method is to use environment variable string substitiution:

set work=%string:substring=%
if not "%work%" EQU "%string%" @echo %string% contains substring
.

If the substring is an environment variable, set work=%string:%substring%=%
or set work=%%string:%substring%=%% does NOT work.
You can use the FOR command to parse this expression,
but using the CALL command is much easier:

call set work=%%string:%substring%=%%
if not "%work%" EQU "%string%" @echo %string% contains %substring%
.

Example

If you need a quick way to determine if a folder is included in your very long SYSTEM PATH,
run CheckPath Folder, i.e; checkpath "c:\program files\support tools".

CheckPath.bat uses Reg.exe from the Windows 2000 Support Tools,
or from %WinDir%\System32 of a Windows XP Professional installation,
or from Supplement 4 of the Windows NT 4.0 Resource Kit, to retireve the SYSTEM PATH.

CheckPath.bat contains:

@echo off
setlocal
if \{%1\}==\{\} goto syntax
set fold=%1
:: Strip quotes and various combinations of trailing \ and double ;
set folder=%fold:"=%\##
set folder=%folder:\\##=%
set folder=%folder:\##=%
set folder=%folder%;##
set folder=%folder:;;##=%
set folder=%folder:##=%\##
set folder=%folder:\\##=%
set folder=%folder:\##=%
set folder=%folder%;##
set folder=%folder:;;##=%
set folder=%folder:##=%
:: Retrieve System Path.
for /f "Skip=2 Tokens=1,2*" %%i in ('REG QUERY "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v PATH') do set syspath=%%k
:: Force trailing ;
set workpath=%syspath%\##
set workpath=%workpath:\\##=%
set workpath=%workpath:\##=%;
call set work=%%workpath:%folder%=%%
if "%work%" EQU "%workpath%" goto :end
@echo Found %fold% in path=%syspath%
goto :end
:syntax
@echo Syntax: CheckPath Folder
:end
endlocal


Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish