Just Code‎ > ‎

Batch - Automatically set JAVA_HOME to current installed version of java

posted Feb 4, 2016, 7:32 AM by Peter Henell   [ updated Feb 4, 2016, 7:32 AM ]
This script will set the user environment variable JAVA_HOME to the path of the current installed Oracle Java.

The current java version is read from the registry at:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\CurrentVersion
@echo OFF

set KEY_NAME="HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE_NAME=CurrentVersion

FOR /F "usebackq tokens=3*" %%A IN (`REG QUERY %KEY_NAME% /v %VALUE_NAME%`) DO (
    set currentVersion=%%A %%B
FOR /F "usebackq tokens=3*" %%A IN (`REG QUERY %KEY_NAME%\%currentVersion% /v JavaHome`) DO (
    set regJavaHome=%%A %%B
ECHO %regJavaHome%

ECHO Setting JAVA_HOME to %regJavaHome%. You will need to restart CMD for this to take effect.
ECHO You can Exit the script now if you do not wish to set this variable.
SETX JAVA_HOME "%regJavaHome%"
ECHO done.