“这一次出乎意料”仅在单台计算机上发生 [英] "was unexpected at this time" happens only on single computer
问题描述
以下命令行(在批处理文件中执行)存在问题:
We have got a problem with the following command line (it is executed in a batch file):
for /f tokens^=3^ delims^=.-_^" %%j in ('cmd /c "%JAVA_HOME%\bin\java.exe" -version 2^>^&1 ^| findstr /i "version"') do set "jver=%%j"
执行此行时,获得Java版本,每次都可以使用,但是现在我们有一台装有Windows 10的计算机,该计算机无法执行脚本,并在此行失败并显示:
When we execute this line, we get the java version. This works everytime, but now we have a computer here with Windows 10 which can not execute the script and fails at this line and says:
8 was unexpected at this time
所以我认为脚本可以读取1.8.0_101 Java版本字符串,但由于某种原因失败。jver变量仅在以下情况中使用一次:
So i assume the script is able to read the 1.8.0_101 java version string but somehow fails. The jver variable is used only once in:
if %jver% LSS 8 (
goto :jdk_wrong_version
)
有人知道为什么这种奇怪的行为吗因为几乎所有机器都对此命令没有问题,所以执行java -version时的输出似乎很好。
Does anybody know why this strange behavior occurs? Because nearly all machines have no problem with this command. The output when we execute java -version seems fine.
编辑:
以下行在开始时执行(因此我们检查JAVA_HOME是否可用):
Following lines are executed at the start (So we check if JAVA_HOME is available):
"%JAVA_HOME%\bin\java.exe" -version 1> NUL 2> NUL
if not %errorLevel%==0 goto :java_not_found
所以整个脚本看起来像这样:
So the whole script looks like this:
"%JAVA_HOME%\bin\java.exe" -version 1> NUL 2> NUL
if not %errorLevel%==0 goto :java_not_found
for /f tokens^=3^ delims^=.-_^" %%j in ('cmd /c "%JAVA_HOME%\bin\java.exe" -version 2^>^&1 ^| findstr /i "version"') do set "jver=%%j"
if %jver% LSS 8 (
goto :jdk_wrong_version
)
推荐答案
我建议使用以下批处理代码安全地检测确定Java版本时可能出现的所有错误:
I suggest to use the following batch code to safely detect every possible error on determining version of Java:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
if not defined JAVA_HOME (
echo Environment variable JAVA_HOME is not defined.
goto :EOF
)
if not exist "%JAVA_HOME%\bin\java.exe" (
echo File "%JAVA_HOME%\bin\java.exe" does not exist.
goto :EOF
)
for /F "tokens=1-3" %%A in ('"%JAVA_HOME%\bin\java.exe" -version 2^>^&1') do (
if /I "%%A %%B" == "java version" (
set "JavaVersion=%%~C"
goto EvaluateVersion
)
)
echo Failed to determine version of installed Java.
goto :EOF
:EvaluateVersion
echo Java version is: %JavaVersion%
for /F "tokens=2 delims=." %%I in ("%JavaVersion%") do set "jver=%%I"
echo Main version is: %jver%
rem More batch code.
endlocal
Java打印版本以处理 STDERR 而不是处理 STDOUT ,这是 2>& 1
的原因,而转义运算符>
和&
在 FOR 执行的命令行中带有 ^
。
Java prints the version to handle STDERR instead of handle STDOUT which is the reason for 2>&1
with escaping the operators >
and &
with ^
in the command line executed by FOR.
如果可以成功确定Java版本,则输出类似于:
If the Java version could be determined successfully, the output is something like:
Java version is: 1.7.0_55
Main version is: 7
这篇关于“这一次出乎意料”仅在单台计算机上发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!