如何在批处理脚本子例程中获取Java版本? [英] How to get Java version in a batch script subroutine?

查看:94
本文介绍了如何在批处理脚本子例程中获取Java版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自此问题:

for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
    @echo Output: %%g
    set JAVAVER=%%g
)

如何将其放入子例程并调用它,将路径传递给Java可执行文件?这是我的问题的一个示例:

How can I put this into a subroutine and call it, passing a path to the java executable? Here's an example of my problem:

@echo off
setlocal enabledelayedexpansion

call :GET_JAVA_VER "java"
goto END

:GET_JAVA_VER
    for /f "tokens=3" %%g in ('%1 -version 2^>^&1 ^| findstr /i "version"') do @echo %%g
    %1 -version 2>&1 | findstr /i "version"
goto :EOF

:END
    endlocal

这将输出:

The filename, directory name, or volume label syntax is incorrect.
java version "10.0.1" 2018-04-17

在我看来,for循环正在对参数(%1)进行不同的计算.

It seems to me that the for loop is evaluating the parameter (%1) differently.

有什么区别?

编辑

Java版本在批处理文件中的可能副本

根据此答案,如果确实存在问题,我将不得不以某种方式转换传入的路径在每个包含空格的目录周围添加引号.这听起来很痛苦,我希望还有另外一种解释.我仍然不明白为什么在这种情况下仅传递"java"是行不通的.

According to this answer, if that is indeed the problem, I would have to somehow transform the passed in path by adding quotes around each directory containing spaces. That sounds like a pain and I'm hoping there's another explanation; I still don't get why in this case just passing in "java" doesn't work.

(注意:使用usebackq和反引号没有区别)

(Note: using usebackq and back-quotes makes no difference)

推荐答案

似乎出于某种原因将输出管道输送到findstr会导致引号被剥夺.我之所以这样推断,是因为当我删除^| findstr /i "version"部分时,是这样的:

It seems that piping the output to findstr was stripping the quotes for some reason. I deduce this because when I removed the ^| findstr /i "version" portion, this:

@echo off
setlocal enabledelayedexpansion

call :GET_JAVA_VER "java"
goto END

:GET_JAVA_VER
    for /f "tokens=3" %%g in ('%1 -version 2^>^&1') do @echo %%g
goto :EOF

:END
    endlocal

输出以下内容:

"10.0.1"
Runtime
64-Bit


此修改后的脚本有效(也具有完整路径):


This modified script works (with full paths as well):

@echo off
setlocal enabledelayedexpansion

call:GET_JAVA_VER "java"
goto END

:GET_JAVA_VER
    for /f "tokens=3" %%g in ('%~1 -version 2^>^&1') do (
        echo %%~g
        rem Stop after first line
        goto :EOF
    )
goto :EOF

:END
    endlocal

这篇关于如何在批处理脚本子例程中获取Java版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆