# Resolves a working Python 3.11+ interpreter for PowerShell scripts and hooks. # Dot-source this file, then call Get-PythonCommand. Candidates are probed by running them, # so the Windows Store "App execution alias" stub (which exists on PATH but only prints an # install hint) is rejected instead of being mistaken for Python. The `py -3` launcher is # tried last for Windows installations that do not put python.exe on PATH. $script:ResolvedPythonCommand = $null function Get-PythonCommand { param([switch]$Required) if ($null -ne $script:ResolvedPythonCommand) { return $script:ResolvedPythonCommand } $previousErrorActionPreference = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { foreach ($candidate in @(@('python'), @('python3'), @('py', '-3'))) { $application = Get-Command $candidate[0] -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1 if (-not $application) { continue } $prefix = @($candidate | Select-Object -Skip 1) try { & $application.Source @prefix -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' *> $null $probeExitCode = $LASTEXITCODE } catch { $probeExitCode = 1 } if ($probeExitCode -eq 0) { $script:ResolvedPythonCommand = [pscustomobject]@{ Path = $application.Source; Arguments = $prefix; Display = ($candidate -join ' ') } return $script:ResolvedPythonCommand } } } finally { $ErrorActionPreference = $previousErrorActionPreference } if ($Required) { throw (Get-PythonMissingMessage) } return $null } function Get-PythonMissingMessage { return 'Python 3.11 or newer was not found (tried python, python3, py -3). A Windows Store app execution alias does not count; install Python, or disable the python/python3 aliases under Settings > Apps > Advanced app settings > App execution aliases.' } # Runs Python with the given arguments; stdin is inherited, so pipe input with Get-PythonCommand instead. function Invoke-Python { $python = Get-PythonCommand -Required & $python.Path @($python.Arguments) @args }