How to get the Java version in PowerShell

最后都变了- 提交于 2019-11-30 13:14:41
CB.

One way is using WMI:

$javaver =  Get-WmiObject -Class Win32_Product -Filter "Name like 'Java(TM)%'" | Select -Expand Version

Another one is redirect to a file with start-process:

start-process  java  -ArgumentList "-version" -NoNewWindow -RedirectStandardError .\javaver.txt

$javaver = gc .\javaver.txt

del .\javaver.txt

And my last is:

dir "HKLM:\SOFTWARE\JavaSoft\Java Runtime Environment"  | select -expa pschildname -Last 1

Regarding how redirect stderr in this case you can do:

$out = &"java.exe" -version 2>&1
$out[0].tostring()

I have been using Get-Command to get Java version on PowerShell 5.1.

Get-Command java | Select-Object Version

This returns an object. If you want a string instead, use:

(Get-Command java | Select-Object -ExpandProperty Version).toString()

The outputs look like this:

PS > Get-Command java | Select-Object Version

Version
-------
8.0.1710.11



PS > Get-Command java | Select-Object -ExpandProperty Version

Major  Minor  Build  Revision
-----  -----  -----  --------
8      0      1710   11



PS > (Get-Command java | Select-Object -ExpandProperty Version).tostring()
8.0.1710.11

It worked quite well under PowerShell 5.1. I don't have a chance to test this on PowerShell 2.0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!