Search code examples
windowsbatch-filejava-home

A script to check the java version and java home


I'm a MR tool admin I need a batch script to satisfy the below requirements

  1. It must check whether Java home is set in Computer > properties (right click) > Advanced system settings > Advanced > Environment Variables.

    If Java home is available it needs to display "Java home is available" else "Java home is not available".

  2. It must check the java version using and if it is greater than 1.6.495 it must display "Java version is too high" else "Java version is compatible".

Currently I'm using a script as given below... Can anyone please please help for making the above script?

@echo off
IF "%JAVA_HOME%" == "" (
    echo Enter path to JAVA_HOME: 
    set /p JAVA_HOME=
) ELSE (
    echo %JAVA_HOME%
)

Solution

  • Give this a whirl ...

    I wasn't quite sure what you mean by "java home is available". The script checks that the directory pointed to by %JAVA_HOME% contains a bin\java.exe.

    The tricky bit is getting the version. I took the output of java -version and used FIND to pick up the first line which is something like java version "1.7.0_55" on my system. java -version writes this to stderr rather than stdout, hence the error redirect (2>& 1 redirects error output to standard output) before piping to FIND. That mess is then redirected into a temp file. Then I used a SET /p with input redirected from the temp to put that output into a variable.

    @echo off
    SETLOCAL
    SET TEMPFILE=%TEMP%\tmpfile
    IF "%JAVA_HOME%" == "" (
        echo Enter path to JAVA_HOME:
        set /p JAVA_HOME=
    ) ELSE (
        echo JAVA_HOME = %JAVA_HOME%
    )
    
    IF EXIST "%JAVA_HOME%\bin\java.exe" (
        ECHO Java home is available
    ) ELSE ECHO Java home is not available
    
    "%JAVA_HOME%\bin\java" -version 2>& 1 | FIND "java version" > %TEMPFILE%
    SET /p VERSIONSTRING= < %TEMPFILE%
    DEL %TEMPFILE%
    SET MAJORVERSION=%VERSIONSTRING:~14,1%
    SET MINORVERSION=%VERSIONSTRING:~16,1%
    SET UPDATEVERSION=%VERSIONSTRING:~20,-1%
    IF %MAJORVERSION% GTR 1 GOTO TOOHIGH
    IF %MINORVERSION% GTR 6 GOTO TOOHIGH
    IF %UPDATEVERSION% GTR 495 GOTO TOOHIGH
    ECHO Java version is compatible.
    GOTO EXIT
    
    :TOOHIGH
    ECHO Java version is too high.
    
    :EXIT
    ENDLOCAL