Windows – Prevent setx to expand an environment variable

environment-variablespathwindows

I can add to the PATH variable from the console using the following command:

setx PATH "%JAVA_HOME%\bin;%PATH%" /m

However, when I check the PATH variable afterwards the JAVA_HOME variable has been expanded so that the actual PATH looks like X:\Path\To\Java\bin;... instead of %JAVA_HOME%\bin;.... Is there a way to use setx like I do here without having the JAVA_HOME variable expanded?

Tried using double %% but that just gave me the expanded version with a percentage on each end. Also tried \%, but that just messed it up.

Best Answer

The command shell escapes with the ^ character, so what you need is to escape the % characters like so: ^%. Try this as a replacement command line:

setx PATH ^%JAVA_HOME^%\bin;"%PATH%" /m

Be careful though, where %PATH% is getting expanded.

EDIT

I think this is a safer way to do it. The first can be pasted right into a command prompt:

FOR /F "usebackq skip=2 tokens=2,*" %i IN (`REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) DO set origpath=%j
SET newpath=^%JAVA_HOME^%\bin;%origpath%
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /f /v Path_ /t REG_EXPAND_SZ /d "%newpath%

And this version can be used in a batch file:

FOR /F "usebackq skip=2 tokens=2,*" %%i IN (`REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) DO set origpath=%%j
SET newpath=%%JAVA_HOME%%\bin;%origpath%
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /f /v Path_ /t REG_EXPAND_SZ /d "%newpath%

In both cases, please test and be careful on production systems. I believe I got all the funky escaping correct, but I may have missed something. Also note the missing trailing " on the end of both line 3's is intentional. You should also be able to modify it to run against remote systems by prepending \\HOSTNAME\ in front of HKEY_LOCAL_MACHINE.