Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
Ben Avatar asked Aug 17 '11 01:08

Ben


People also ask

How do you clear a variable in CMD?

Therefore you cannot save your changes. However, you can clear the value of an environment variable using Command Prompt. To unset an environment variable from Command Prompt, type the command setx variable_name “”. For example, we typed setx TEST “” and this environment variable now had an empty value.


2 Answers

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%
like image 117
Harry Johnston Avatar answered Sep 19 '22 05:09

Harry Johnston


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.

like image 36
Michael Burr Avatar answered Sep 18 '22 05:09

Michael Burr