How to set an environment variable dependent on another one? (Windows)

Viewed 4658

I am looking for a way on Windows how to set an environment variable dependent on another one. In my case, I want to add the new path to PYTHONPATH. Let's say, that there is an existing environment variable

%INSTALLATION_DIR% = D:\Programs\MyProject

The easiest way to do that would be:

SETX PYTHONPATH "%PYTHONPATH%;%INSTALLATION_DIR%\Utility\Scripts"

But then, %INSTALLATION_DIR% is directly replaced by D:\Programs\MyProject, so PYTHONPATH is not updated if %INSTALLATION_DIR% changes.

Is there a way to write the text %INSTALLATION_DIR% into an environment variable, without evaluating the variable directly?

If possible, I want to do that in an automated way (so using the console, powershell or python), as a want to write a script which adds a list of paths to PYTHONPATH.

2 Answers

I just found the solution. If the name of the environment variable is written in quotes, it will not be evaluated.

SETX PYTHONPATH "%PYTHONPATH%;%"INSTALLATION_DIR"%\Utility\Scripts"

treat the % as you would treat a special character. double the % so

SETX PYTHONPATH "%PYTHONPATH%;%%INSTALLATION_DIR%%\Utility\Scripts"

Related