Powershell script to check if Python is installed

社会主义新天地 提交于 2021-02-08 08:44:15

问题


I'm trying to check if Python is installed on a machine via a Powershell script.

My idea so far is to run the following:

$p = iex 'python -V'

If the command executes correctly (check the Exitcode on $p property), read the output and extract the version number.

However, I'm struggling to capture the output when executing the script in Powershell ISE. It's returning the following:

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

Can someone point in the right direction?

Cheers, Prabu


回答1:


It seems that python -V outputs the version string to stderr and not stdout.

You can use a stream redirector to redirect the error into the standard output:

# 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
}

If you are certain that all the versions of python you have on your systems will behave this way, you can cut it down to:

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


来源:https://stackoverflow.com/questions/36953800/powershell-script-to-check-if-python-is-installed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!