2

I want to easily switch between different java versions and therefore want to set home path and path at system level in enviroment variables by running a bat/cmd file.

My .bat file looks like this:

@echo off  
echo Setting JAVA_HOME  
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0
echo JAVA_HOME: %JAVA_HOME% 
echo setting PATH
set PATH=%JAVA_HOME%\bin;%PATH% 
echo PATH: %PATH%  

If i type echo %JAVA_HOME% in same commandprompt then it prints the path to jdk1.8.0 but not if i open up a new commandprompt, also if i look in enviroment variables it is not listed there.

EDIT: I've also tried

@echo off  
echo Setting JAVA_HOME  
setx JAVA_HOME "C:\Program Files\Java\jdk1.8.0"
echo JAVA_HOME: %JAVA_HOME% 
echo setting PATH
setx PATH "%JAVA_HOME%\bin;%PATH%"
echo PATH: %PATH%  
echo Display java version  
java -version  

And this works, at the user level, but not at the system level.

2 Answers 2

6

Solved it by:

@echo off  
echo Setting JAVA_HOME  
setx -m JAVA_HOME "C:\Program Files\Java\jdk1.8.0"
echo JAVA_HOME: %JAVA_HOME% 
echo setting PATH
setx -m PATH "%Path%;%JAVA_HOME%\bin"
echo PATH: %PATH%  
echo Display java version  
java -version  
pause
Sign up to request clarification or add additional context in comments.

Comments

1

Note that setx does not have an = sign. If you have

setx abc=def

It will set the variable abc=def to nothing. If you wish to set abc to def, the syntax is

setx abc def

What you are seeing is the correct behaviour when you run the batch file with set. To set the environment variables globally

@echo off  
echo Setting JAVA_HOME  
setx JAVA_HOME "C:\Program Files\Java\jdk1.8.0"
echo JAVA_HOME: %JAVA_HOME% 
echo setting PATH
setx PATH %JAVA_HOME%\bin;%PATH% 
echo PATH: %PATH%

Note that there is no = after the variable when you use setx

2 Comments

Thank, you. I've already tried that, and that works at the user level. But not at the system level.
For a system level variable, use setx /m

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.