2016-04-30 90 views
1

我想检查是否Python通过Powershell脚本安装在一台机器上。Powershell脚本来检查是否Python安装

我的想法到目前为止是运行以下命令:

$p = iex 'python -V' 

如果命令正确执行(检查Exitcode$p属性),读取输出,并提取版本号。

但是,我很努力捕获Powershell ISE中执行脚本时的输出。它返回以下内容:

python : Python 2.7.11 
At line:1 char:1 
+ python -V 
+ ~~~~~~~~~ 
    + CategoryInfo   : NotSpecified: (Python 2.7.11:String) [], RemoteException 
    + FullyQualifiedErrorId : NativeCommandError 

有人能指向正确的方向吗?

干杯, Prabu

+0

检查'$ LASTEXITCODE'自动变量 –

+0

@ MathiasR.Jessen这给了我,如果表达式成功运行一个布尔值的价值,我相信。但是,如何从表达式本身提取控制台输出 - 因此我可以获取版本号? –

回答

1

似乎python -V输出版本字符串stderr,而不是stdout

可以使用流重定向到错误重定向到标准输出:

# redirect stderr into stdout 
$p = &{python -V} 2>&1 
# check if an ErrorRecord was returned 
$version = if($p -is [System.Management.Automation.ErrorRecord]) 
{ 
    # grab the version string from the error message 
    $p.Exception.Message 
} 
else 
{ 
    # otherwise return as is 
    $p 
} 

如果你确信所有的Python的你有你的系统版本将这样的行为,你可以对它进行切割到:

$version = (&{python -V}).Exception.Message 
+0

谢谢 - 作品像魅力。 –

+0

请注意'$ p -is [System.Management.Automation.ErrorRecord]'依靠Python只写入stderr。如果它也写入stdout,那么'$ p'是一个数组,'-is'失败。因此,稍微安全的替代方案是'$ version =($ p |%gettype)-eq [System.Management.Automation.ErrorRecord]',然后处理'$ version'为非空(具有stderr输出)和null (没有stderr输出) –

+0

这就是我写第一个例子的确切原因:-) –

相关问题