5

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.

1 Answer 1

4

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.

4
  • 1
    So existing environment variables in PATH will be expanded as well? Is there a way to avoid that then? Would be nice to only append/prepend a value to PATH without changing anything existing in it :S Commented Apr 24, 2013 at 8:04
  • 1
    I'm not sure if you can do what you're asking with setx. What about if you instead read the existing Path value from HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment, prepend your string to it, and write it back? Commented Apr 25, 2013 at 3:10
  • Can you do that from the console? Commented Apr 25, 2013 at 10:04
  • See my edits above, I think they may be a better approach. Commented Apr 26, 2013 at 2:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.