How to get Java version in PowerShell

I am trying to get the Java version in PowerShell. The version string prints to stderr , so I'm trying to redirect it to stdout and assign it to a string variable.

I get the following strange error:

PS P:\> & java -version 2>&1 java.exe : java version "1.7.0_25" At line:1 char:2 + & <<<< java -version 2>&1 + CategoryInfo : NotSpecified: (java version "1.7.0_25":String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError Java(TM) SE Runtime Environment (build 1.7.0_25-b17) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) 

A call without redirection (2> & 1) gives the following:

 PS P:\> & java -version java version "1.7.0_25" Java(TM) SE Runtime Environment (build 1.7.0_25-b17) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) 

I think Java doesn't matter here, and the same thing will happen for any other program that prints lines in stderr.

Used version of PowerShell 2.0 .

Questions:

  • How can I redirect stderr to a variable?
  • Or alternatively, how can I check the installed version of Java?

Bypass

I can run it like this:

 $output = & cmd /c "java -version 2>&1" 

But I hate running cmd.exe where it is not needed.

+7
java powershell version
source share
1 answer

One way: WMI :

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

Another is redirecting to a file with the initial process:

 start-process java -ArgumentList "-version" -NoNewWindow -RedirectStandardError .\javaver.txt $javaver = gc .\javaver.txt del .\javaver.txt 

And the last one:

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

Regarding how to redirect stderr in this case, you can do:

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

All Articles