powershell java,如何在PowerShell中获取Java版本

在PowerShell 2.0中,用户尝试从stderr获取Java版本信息时遇到问题。他们试图使用重定向将stderr输出到stdout并赋值给变量,但遇到了错误。用户还分享了几个工作原理不同的解决方法,包括使用WMI、通过启动进程重定向和读取注册表键。他们希望找到不依赖cmd.exe的解决方案。
摘要由CSDN通过智能技术生成

I'm trying to get the Java version in PowerShell. The version string is printed 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)

Call without redirection (2>&1) gives this:

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 that Java here is irrelevant, and the same would happen for any other program printing strings to stderr.

The PowerShell version I use is 2.0.

Questions:

How can I redirect stderr to a variable?

Or, alternatively, how can I check the installed Java version?

Workaround

I can run it like this:

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

But I hate running a cmd.exe where it shouldn't be necessary.

解决方案

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值