3

I am trying to upgrade Java with a batch file, and I need to change the PATH system variable to reflect that change. At the beginning of the PATH variable I have

C:\Program Files\Java\jdk1.8.0_51;...

I need to change the jdk value to be jdk1.8.0_60. I'm relatively new to command line and batch files, and so I may be misunderstanding something. Here is what I am trying.

I have a couple variables

jVersion=1.8.0_
javaPath=C:\Program Files\Java
newVersion=60
oldVersion=51

I found something about replacing strings with literal values like so

set PATH=%PATH:1.8.0_51=1.8.0_60%

but I can't get it to work with variables...

set PATH=%%PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%%%

I don't know if you need 2 %'s around the outside, or just one, or !'s. I'm not super confident in my knowledge of delayed expansion. I also don't know if this is possible.

As a bonus, I would really like to be able to take whatever comes after ...\Java\ and replace it with my new value. This would be just in case I don't know the value in the PATH variable for the jdk

Thanks!

EDIT: By using the command call before a modified version of my code I was able to get it to work

call set PATH=%PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%%

I'm still trying to figure out how to make it generic and change whatever comes after ...\jdk to the values I have.

Alex Johnson
  • 504
  • 5
  • 15

3 Answers3

2

paste the Below Code in a bat file and that should solve the problem

@echo off

setlocal EnableDelayedExpansion
set jVersion=1.8.0_
set "javaPath=C:\Program Files\Java"
set newVersion=60
set oldVersion=51
set PATH=%jVersion%%oldVersion%
echo before path change : !PATH!
set PATH=!PATH:%jVersion%%oldVersion%=%jVersion%%newVersion%!
echo final path change  : !PATH!
pause
prudviraj
  • 3,634
  • 2
  • 16
  • 22
1

This is not exactly what you want to do but might solve the problem. Create a new environment variable called JAVA_HOME and let it point to your java installation folder. From now on manipulate this JAVA_HOME variable instead. You can replace it every time with your script. Edit your PATH environment variable (only once) so that it includes this new JAVA_HOME variable like this PATH=%JAVA_HOME%\bin;

-1

I think you want this:

set PATH=C:\Program Files\Java\jdk1.8.0_60;%PATH%

if you put the new JDK in the path before the current one, the OS will use the new JDK.

But you would be far better off editing your PATH system setting and replacing the old JDK path with the new old.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Yeah this would work, but would increase the size of the path unnecessarily after time. I agree replacing it would be better. Thanks – Alex Johnson Oct 09 '15 at 14:55