7

I've got a batch file that modifies the PATH variable by prepending a few addresses. When the user logs off-then-on, PATH is reset to its original value (before the batch file was ever run). This behavior is OK.

However, if the batch file is run more than once, the same values are re-prepended and I end up with a overly long, redundant PATH variable that just gets longer after each batch run.

I'd like to reset the variable to whatever it is when the user logs on, before the values are prepended. I figure the solution is to write the original value in a temp file and read it back, but is there a better way to do it?

3 Answers 3

7

Rather than writing the original value to a temp file, you could write it to another environment variable:

if not defined ORIGINAL-PATH set ORIGINAL-PATH=%PATH%
set PATH=c:\extra\stuff;%ORIGINAL-PATH%

but it would be better to explicitly check whether the string you want is in PATH already or not, like this:

echo %PATH% | findstr /c:"c:\extra\stuff;" > nul || set PATH=c:\extra\stuff;%PATH%
Sign up to request clarification or add additional context in comments.

2 Comments

This is actually what I ended up doing. Thanks!
This has the added benefit of if you screw up the "extra-stuff"..you can fix it. I forgot the trailing "\" when I first did it. Thanks for the simple but effective tip!
6

Put @SETLOCAL at the top of your batch file.

Any changes made to the environment will be restored when the batch file exits.

Run setlocal /? for more details.

Comments

1

I've been looking for a solution for long time for a similar problem. Finally I ended up using the pathmgr.cmd which I've downloaded from:

http://gallery.technet.microsoft.com/Batch-Script-To-Manage-7d0ef21e

To use it to clean the user PATH, the below options can be used from command line:

pathmgr.cmd /clean /user /p /y

Many other useful options are also available.

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.