Batch - Automatically set JAVA_HOME to current installed version of java

Post date: Feb 4, 2016 3:32:04 PM

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 OFFsetlocal ENABLEEXTENSIONS 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.PAUSE SETX JAVA_HOME "%regJavaHome%"ECHO done.pause