用于检查 Python 是否已安装的 Powershell 脚本

Pra*_*abu 1 python powershell

我正在尝试通过 Powershell 脚本检查机器上是否安装了 Python。

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

$p = iex 'python -V'
Run Code Online (Sandbox Code Playgroud)

如果命令正确执行(检查Exitcodeon$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
Run Code Online (Sandbox Code Playgroud)

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

干杯,普拉布

Mat*_*sen 5

似乎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
}
Run Code Online (Sandbox Code Playgroud)

如果您确定系统上的所有 python 版本都会以这种方式运行,您可以将其缩减为:

$version = (&{python -V}).Exception.Message
Run Code Online (Sandbox Code Playgroud)