Reputation: 959
I am writing a batch script that, quite reasonably, depends on "C:\WINDOWS\system32" being part of the PATH environment variable. I recently encountered a (developer's) machine that had a really weird path that didn't include system32, and therefore my batch script didn't work.
I looked up ways for my batch script to check the PATH variable and add system32 if it is not there. However, the solution I found used setx
which ironically enough ALSO depends on system32 in the PATH variable. Are there any programmatic ways to add system32 to the PATH without it already being there?
Also please let me know if this is such an edge case that it doesn't make sense to make my script robust against it. I'm not expecting any of my typical users to have such a borked PATH variable. Should I bother?
Upvotes: 1
Views: 5435
Reputation: 80043
@ECHO OFF
SETLOCAL
SET "required=c:\windows\system32"
for %%p in ("%path:;=" "%") do (
FOR %%j IN ("" \) DO (
IF /i %%p=="%required%%%~j" GOTO :nextstep
)
)
SETx PATH "%required%;%path%"
:nextstep
ECHO PATH=%path%
GOTO :EOF
Here's my take on the problem. PATH
may contain the required directory with or without a trailing \
, and it may or may not have a preceding or trailing ;
I'd suggest that you examine the operation of SETX
however. It sets an environment variable for FUTURE cmd sessions, not the CURRENT or EXISTING sessions, AFAIAA....and perhaps not for PATH
or some other variables (I tried setting PATH
using the SETX
in the above batch - future sessions did NOT acquire the new value set, but it appeared to be set according to regedit32
- perhaps it needs a reboot - haven't investigated further at this stage)
Note that the above will need to have the required directory appended to %path%
if my observations are borne out...
Upvotes: -1
Reputation: 37569
try this:
for /f "delims=" %%a in ("%comspec%") do set "PATH=%PATH%;%%~DPa"
or this:
for /f "delims=" %%a in ("%comspec%") do set "compath=%%~DPa"
set "PATH=%PATH%;%compath:~0,-1%"
Upvotes: 2