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?
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.
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%
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With