The java -version
command writes it's output to the standard error stream instead of the std output stream (which is why you see that error). In powershell, the error stream is not passed along the pipeline. A workaround that works is to create a simple windows batch file that redirects the error stream to the output stream. For example, create a file caled getJavaVersion.bat
that looks like this:
@echo off
"C:\Program Files (x86)\Java\jre7\bin\java.exe" -version 2>&1
Then, you can call that directly from powershell as you expect:
PS C:\Temp> $out = .\getJavaVersion.bat
PS C:\Temp> $out
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
Java HotSpot(TM) Client VM (build 23.1-b03, mixed mode, sharing)
If you don't want to create that extra file, then you can call cmd.exe
directly to get the same results:
$out = cmd.exe /c '"C:\Program Files (x86)\Java\jre7\bin\java.exe" -version 2>&1'
Or you can redirect the StdERR output directly into $out, which will put each of the error objects (2 in this case) into $out (recast as an array). You can then read each, or the best one for you, back for use:
$out = &"C:\Program Files (x86)\Java\jre7\bin\java.exe" -version 2>&1
$out.Count // Show number of errors returned
$out[1] // Show second error in array.
Output:
2
Java(TM) SE Runtime Environment (build 1.7.0_05-b05) Java HotSpot(TM)
Client VM (build 23.1-b03, mixed mode, sharing)
Related: Using powershell call native command-line app and capture STDERR