1

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?

2 Answers 2

2

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%"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was pretty confused what was going on here at first, but I figured it out: %comspec% contains the path the the command line executable: "C:\WINDOWS\system32\cmd.exe". The for loop allows us to use %%~DPa to format this to "C:\WINDOWS\system32" without the filename. Then we set the path to the old path with this appended. We don't need to check if it's already in the path because this addition only lasts for the duration of the session anyway.
-1
@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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.