kiss my armpit
kiss my armpit

Reputation: 3519

How to append a list of directories provided in a text file to PATH variable?

I have a text file list.txt consisting of directories as follows.

C:\Program Files\gs\gs9.07\bin
C:\Program Files (x86)\Adobe\Reader 11.0\Reader
C:\Program Files (x86)\Google\Chrome\Application
C:\Program Files (x86)\cwRsync\bin
C:\Program Files (x86)\PDF Labs\PDFtk Server\bin

I want to create a batch file that appends each item in list.txt to system PATH environment variable permanently.

My failed attempt is as follows.

rem batch.bat
for /f "delims=" %%x in (list.txt) do (setx PATH "%PATH%;%%x" /m)

I invoke batch.bat with administrative privilege but nothing appended to PATH. Could you help me solve it?

Upvotes: 0

Views: 220

Answers (1)

Magoo
Magoo

Reputation: 80211

@ECHO OFF
setlocal
SET testvar=%PATH%
FOR /f "delims=" %%x IN (list.txt) DO (
CALL SET testvar=%%testvar%%%%x;
)
setx testvar "%testvar%"

Well - this sets 'testvar' for future invocations - I don't want to change my PATH; existing instances, including the current, will be unchanged (as documented.)

The problem with your implementation is that when a FOR loop is parsed, any %var% is replaced by its then-existing value before the loop is executed. In consequence, your command was executed as

setx path "(yourexistingpath);C:\Program Files\gs\gs9.07\bin"
setx path "(yourexistingpath);C:\Program Files (x86)\Adobe\Reader 11.0\Reader"
...

which should have set your path according with the final line from your file (only) appended.

...and of course all you need to do to set TESTVAR in the CURRENT environment is to remove the SETLOCAL (which is actually only there to keep my environment clean while testing) OR to add a line

ENDLOCAL&set testvar=%testvar%

Upvotes: 1

Related Questions