1

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

Prabu
  • 4,097
  • 5
  • 45
  • 66
  • Check the value of the `$LASTEXITCODE` auto variable – Mathias R. Jessen Apr 30 '16 at 11:04
  • @MathiasR.Jessen That gives me a boolean value if the expression ran successfully, I believe. However, how do I extract the console output from the expression itself - so I can get the version number? – Prabu Apr 30 '16 at 11:15
  • Does this answer your question? [Python Version in PowerShell](https://stackoverflow.com/questions/42407894/python-version-in-powershell) – halt9k Jan 16 '23 at 19:31

2 Answers2

5

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
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Note that `$p -is [System.Management.Automation.ErrorRecord]` relies on Python only writing to stderr. If it writes to stdout as well, then `$p` is an array and `-is` fails. So a slight safer alternative is `$version = ($p | % gettype) -eq [System.Management.Automation.ErrorRecord]`, then handling the cases of `$version` being non-null (has stderr output) and null (doesn't have stderr output) – Χpẘ May 01 '16 at 15:56
  • That's the exact reason I wrote the first example as is :-) – Mathias R. Jessen May 01 '16 at 16:02
0

For python above 3.3, a launcher was introduced which may be installed automatically or manually as part of official installer.

In modern situation, command python -V may give you error or nothing helpful (python may not even be presented in PATH by default), but launcher is supposed to be used both for checking installed python versions:

py -0p --list-paths

and to run scripts: py -3.11 main.py or simply py main.py

Discussion which confirms.

halt9k
  • 527
  • 4
  • 13