5

我正在寻找一个批处理文件片段,它以某种方式读取 Windows 注册表并检测 Windows 系统上的 Java JDK,然后询问用户他们想要使用哪个并记住选择。

这是我到目前为止所拥有的......需要一些修改。这个脚本只找到第一个 JDK ......它不处理倍数。

@echo off
SETLOCAL EnableDelayedExpansion
:: findJDK.bat
start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit" 
type reg1.txt | find "JavaHome" > reg2.txt 
if errorlevel 1 goto ERROR 
for /f "tokens=2 delims==" %%x in (reg2.txt) do (
  set JavaTemp=%%~x
  echo Regedit: JAVA_HOME path : !JavaTemp!
)
if errorlevel 1 goto ERROR
echo.
set JAVA_HOME=%JavaTemp%
set JAVA_HOME=%JAVA_HOME:\\=\%
echo JAVA_HOME was found to be %JAVA_HOME%
goto END
:ERROR
echo reg1.txt is: & type reg1.txt
echo reg2.txt is: & type reg2.txt
echo
:END
del reg2.txt
del reg1.txt
pause>nul
4

3 回答 3

2

您可以检查注册表中 HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment 下的条目

于 2010-01-14T10:04:44.703 回答
2

好的,我终于找到了答案。花了一些时间,这段代码确实很粗糙,但它确实有效。如果有人想改进它,我会奖励他们答案点:

@ECHO off
SET TITLE=detectJDK.bat
TITLE=%TITLE%
SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST jdkhome.txt (
  ECHO JDK home already set in jdkhome.txt file.
  GOTO :END
)
ECHO. 2>merged.txt
ECHO. 2>list.txt
ECHO. 2>uniquelist.txt
IF NOT EXIST reg32.txt ECHO. 2>reg32.txt
IF NOT EXIST reg64.txt ECHO. 2>reg64.txt
START /w REGEDIT /e reg32.txt "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\JavaSoft\Java Development Kit"
TYPE reg32.txt | FIND "JavaHome" > merged.txt
START /w REGEDIT /e reg64.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit"
TYPE reg64.txt | FIND "JavaHome" >> merged.txt
FOR /f "tokens=2 delims==" %%x IN (merged.txt) DO (
  CALL :STRIP "%%~x" >>list.txt
)

FOR /F "tokens=* delims= " %%a IN (list.txt) DO (
  SET str=%%a
  FIND /I ^"!str!^" list.txt>nul
  FIND /I ^"!str!^" uniquelist.txt>nul
  IF ERRORLEVEL 1 ECHO !str!>>uniquelist.txt
)

ECHO Select a JDK from the list:
SET /A COUNT=0
FOR /f "tokens=1,* delims=" %%y IN (uniquelist.txt) DO (
  SET /A COUNT += 1
  ECHO    !COUNT!: %%~y
)
SET /P NUMBER=Type a number here: 
SET /A COUNT=0
FOR /f "tokens=1,* delims=" %%z IN (uniquelist.txt) DO (
  SET /A COUNT += 1
  IF !COUNT!==!NUMBER! (
    SET JAVA_HOME=%%~z
  )
)
ECHO.
ECHO JAVA_HOME was found to be %JAVA_HOME%
ECHO %JAVA_HOME%>jdkhome.txt
GOTO CLEANUP

:CLEANUP
DEL /Q merged.txt
DEL /Q list.txt
DEL /Q uniquelist.txt
DEL /Q reg32.txt
DEL /Q reg64.txt
GOTO :END

:: Strip quotes and extra backslash from string
:STRIP
SET n=%~1
SET n=%n:\\=\%
SET n=%n:"=%
IF NOT "%n%"=="" ECHO %n%
GOTO :EOF

:END
FOR /l %%a in (5,-1,1) do (TITLE %TITLE% -- Closing in %%as&ping -n 2 -w 1 127.0.0.1>NUL)
:: end
于 2011-10-26T05:53:57.780 回答
0

您真的需要使用 Windows 注册表吗?如果没有,您可以检查JAVA_HOME和/或JDK_HOME环境变量是否存在。如果它们存在,那么它们指向 Java 安装的安装目录,您可以假设它们指向的 Java 安装是用户想要使用的那个。

于 2011-10-17T16:48:30.307 回答