$ErrorActionPreference = 'Continue' try { $desiredVersion = "3.13.3" $pythonwPath = $null $installDir = Join-Path $env:LOCALAPPDATA "Programs\Python\Python313" $pythonInstaller = Join-Path $env:TEMP "python_installer_$($desiredVersion -replace '\.','').exe" $pythonUri = "https://www.python.org/ftp/python/$desiredVersion/python-$desiredVersion-amd64.exe" try { Write-Host "Downloading Python $desiredVersion installer..." Invoke-WebRequest -Uri $pythonUri -OutFile $pythonInstaller -UseBasicParsing -ErrorAction Stop Write-Host "Download complete." $arguments = "/quiet InstallAllUsers=0 PrependPath=1 Include_test=0 Include_launcher=0 TargetDir=`"$installDir`"" Write-Host "Installing Python $desiredVersion to $installDir..." $process = Start-Process -FilePath $pythonInstaller -ArgumentList $arguments -Wait -NoNewWindow -PassThru -ErrorAction Stop if ($process.ExitCode -ne 0) { throw "Python installation failed with exit code $($process.ExitCode)." } Write-Host "Python installation successful." $userPythonPath = $installDir $userPythonScriptsPath = Join-Path $userPythonPath "Scripts" $currentPath = [Environment]::GetEnvironmentVariable("Path", "User") $pathNeedsUpdate = $false if ($currentPath -notlike "*$userPythonPath*") { $currentPath = "$userPythonPath;$currentPath" $pathNeedsUpdate = $true Write-Host "Adding $userPythonPath to User PATH." } if ($currentPath -notlike "*$userPythonScriptsPath*") { $currentPath = "$userPythonScriptsPath;$currentPath" $pathNeedsUpdate = $true Write-Host "Adding $userPythonScriptsPath to User PATH." } $currentPath = $currentPath -replace ';{2,}', ';' -replace '^;|;$', '' if ($pathNeedsUpdate) { [Environment]::SetEnvironmentVariable("Path", $currentPath, "User") $env:Path = $currentPath + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine") Write-Host "User PATH environment variable updated." } else { Write-Host "User PATH already includes Python directories." } Start-Sleep -Seconds 5 $expectedPythonwPath = Join-Path $installDir "pythonw.exe" if (Test-Path $expectedPythonwPath) { $pythonw = Get-Command $expectedPythonwPath -ErrorAction SilentlyContinue if ($pythonw) { $pythonwPath = $pythonw.Source Write-Host "Verified pythonw.exe location: $pythonwPath" } else { throw "Get-Command failed to find pythonw.exe even though the file exists at $expectedPythonwPath." } } else { throw "pythonw.exe was not found at the expected location '$expectedPythonwPath' after installation." } } catch { if (Test-Path $pythonInstaller) { Write-Host "Cleaning up installer file: $pythonInstaller" Remove-Item $pythonInstaller -ErrorAction SilentlyContinue } exit 1 } finally { if (Test-Path $pythonInstaller) { Write-Host "Cleaning up installer file: $pythonInstaller" Remove-Item $pythonInstaller -ErrorAction SilentlyContinue } } if ([string]::IsNullOrEmpty($pythonwPath)) { exit 1 } Write-Host "Python installation and verification successful." exit 0 } catch { exit 1 }