Reputation: 36328
This question expands on the comments on this deleted answer. I claimed that an unexpanded variable reference in the PATH would not be expanded when searching for an executable, but Ken said he didn't see the same behaviour that I did.
Note that the ordinary situation is subtly but critically different: subject to certain conditions, environment variables are automatically expanded when the PATH environment variable is built from the information in the registry. I'm talking about the case where, for one reason or another, this hasn't happened, so the actual environment block of the cmd.exe
process contains a PATH which still has environment variable references in it.
Here is the code I built to test this behaviour:
md test1
echo echo hello! > test1\test1.cmd
set TESTPATH=%cd%\test1
set percent=%%
set PATH=c:\windows\system32;c:\windows;c:\windows\system32\Wbem;%percent%TESTPATH%percent%
set PATH
set TESTPATH
test1
cmd /c test1
start test1.cmd
and this is the result on my machine:
C:\working\testpath>test
C:\working\testpath>md test1
C:\working\testpath>echo echo hello! 1>test1\test1.cmd
C:\working\testpath>set TESTPATH=C:\working\testpath\test1
C:\working\testpath>set percent=%
C:\working\testpath>set PATH=c:\windows\system32;c:\windows;c:\windows\system32\
Wbem;%TESTPATH%
C:\working\testpath>set PATH
Path=c:\windows\system32;c:\windows;c:\windows\system32\Wbem;%TESTPATH%
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.py;.pyw
C:\working\testpath>set TESTPATH
TESTPATH=C:\working\testpath\test1
C:\working\testpath>test1
'test1' is not recognized as an internal or external command,
operable program or batch file.
C:\working\testpath>cmd /c test1
'test1' is not recognized as an internal or external command,
operable program or batch file.
C:\working\testpath>start test1.cmd
The system cannot find the file test1.cmd.
What is the expected behaviour? Does it vary depending on the version of Windows and/or other factors?
Upvotes: 1
Views: 492
Reputation: 67216
There are two entirely different points of view in this question:
A: Enclose the names of the variables in exclamation marks and enable delayed expansion when you want to expand such values:
@echo off
setlocal EnableDelayedExpansion
set TESTPATH=%cd%\test1
set "PATH=c:\windows\system32;c:\windows;c:\windows\system32\Wbem;^!TESTPATH^!"
set PATH
echo PATH=%PATH%
A: No. cmd.exe uses the values in PATH variable as they appear, with no further processing. Any special character that may appear in PATH, like percents or exclamation-marks, are taking literally.
Upvotes: 1