How to install Python of required version using PowerShell

by Dmitry Kirsanov 26. February 2023 11:46

One of the software packages I’m using, namely Stable Diffusion, requires a particular version of Python to work… Stable. Hence I made a little PowerShell script that would ensure that if there is a Python of lower version or it’s not installed, then it would be downloaded and installed automatically. Here it is:

 # Define the required version of Python $RequiredVersion = '3.10.6' # Check if Python is installed and get the version number $CurrentVersion = if (Test-Path 'HKLM:\Software\Python\PythonCore') { Get-ItemProperty 'HKLM:\Software\Python\PythonCore\*' | Select-Object -ExpandProperty Version | Sort-Object -Descending | Select-Object -First 1 } else { $null } # Check if the current version meets the required version if ($CurrentVersion -ge $RequiredVersion) { Write-Host "Python $CurrentVersion is already installed." } else { Write-Host "Python is not installed or the installed version is lower than $RequiredVersion. Installing Python $RequiredVersion..." # Download the Python installer $DownloadUrl = "$RequiredVersion/python-$RequiredVersion-amd64.exe" Invoke-WebRequest -Uri $DownloadUrl -OutFile 'python.exe' # Install Python silently $Arguments = '/quiet', 'TargetDir=C:\Python', 'InstallLauncherAllUsers=1', 'AssociateFiles=1', 'PrependPath=1', 'Include_test=0', 'Include_doc=0' Start-Process -FilePath 'python.exe' -ArgumentList $Arguments -Wait # Remove the installer Remove-Item 'python.exe' Write-Host "Python $RequiredVersion has been installed." } 
blog comments powered by Disqus

Month List