Ben
Ben

Reputation: 57209

Windows CMD - Reset path variable from batch file?

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?

Upvotes: 7

Views: 9625

Answers (3)

user3131978
user3131978

Reputation: 37

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.

Upvotes: 1

Harry Johnston
Harry Johnston

Reputation: 36308

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%

Upvotes: 7

Michael Burr
Michael Burr

Reputation: 340178

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.

Upvotes: 6

Related Questions