6

I want to get output from command C:\Program Files (x86)\Java\jre7\bin\java.exe" -version as string variable.

I tried this way: $out = &"C:\Program Files (x86)\Java\jre7\bin\java.exe" -version

but it gives error message:

java.exe : java version "1.7.0_05"
At line:1 char:9
+ $out = & <<<< "C:\Program Files (x86)\Java\jre7\bin\java.exe" -version
    + CategoryInfo          : NotSpecified: (java version "1.7.0_05":String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Java(TM) SE Runtime Environment (build 1.7.0_05-b05)


Java HotSpot(TM) Client VM (build 23.1-b03, mixed mode, sharing)

$out variable seems empty.

What am I doing wrong?

2 Answers 2

8

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

1
  • So annoying: I wish apps would only write ERRORS to STDERR.
    – Jay Bazuzi
    Jan 21, 2013 at 17:27
2
java -version  2>&1 | foreach-object {$_.tostring()}

redirects stderr to stdout and converts System.Management.Automation.ErrorRecord to System.String.

This works with other command line applications that write to stderr.

1
  • This worked for me! I used it to get the Python version from a PowerShell script: $pythonVersion = python --version 2>&1 | % {$_.ToString()}
    – G. Lombard
    Apr 23, 2014 at 18:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .