How To Pipe Java Version in Batch File

647 views Asked by At

How can I find the java version and set that to a variable?

I've tried this:

for /f "tokens=*" %%a in ('java -version | find "version"') do (set var1=%%a)

but java isn't redirecting its output to find. Another post suggested this solution

java -version 2>&1 | findstr "version" >tmp.txt
for /f "tokens=*" %%x in (tmp.txt) do (set var1=%%x)
echo %var1%
del tmp.txt

but I would like to avoid using the temp file.

1

There are 1 answers

3
aschipfl On

java.exe seems to output the version information at STDERR, so the correct code is:

for /f "tokens=*" %%a in ('java -version 2^>^&1 ^| find "version"') do (set var1=%%a)

As you can see, >, & and | are escaped with ^.