Last active
March 17, 2021 20:24
-
-
Save BuriedStPatrick/4dc37b65b4a92d3b7467b0a33fcfcad0 to your computer and use it in GitHub Desktop.
Update/Install latest Powershell version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Import the module in your profile so that you always have access to Update-Powershell in your session | |
Import-Module Pwsh.pms1 | |
# In your session, you can now call Update-Powershell at any time |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Install-Powershell([string] $version) | |
{ | |
# in case the version was specified with a prefix, strip it | |
$version = $version.Replace('v', '') | |
Write-Host "Downloading $version..." | |
$output = "PowerShell-$version-win-x64.msi" | |
$url = "https://github.com/PowerShell/PowerShell/releases/download/v$version/PowerShell-$version-win-x64.msi" | |
try { | |
$wc = New-Object System.Net.WebClient | |
$wc.DownloadFile($url, $output) | |
} catch [System.Net.WebException],[System.IO.IOException] { | |
throw "Couldn't download release: $($_.Exception.Message)"; | |
} | |
Write-Host "Downloaded $output" | |
Write-Host "Running update $output..." | |
Start-Process $output | |
# Close current session as installer will need all pwsh.exe instances killed | |
$key = Read-Host "Close session (Y/n)?" | |
if(!($key.ToLower() -eq "n")) { | |
exit | |
} | |
} | |
function Update-Powershell([bool] $includePreview = $false) { | |
# Get the latest release tag | |
$releasesUrl = "https://api.github.com/repos/Powershell/Powershell/releases" | |
if($includePreview) { | |
$releases = (Invoke-WebRequest $releasesUrl | ConvertFrom-Json) | Where-Object { $_.tag_name -like "*preview*"} | |
} else { | |
$releases = (Invoke-WebRequest $releasesUrl | ConvertFrom-Json) | Where-Object { $_.tag_name -notlike "*preview*"} | |
} | |
$latestRelease = $releases[0].tag_name.Replace('v', '') | |
$installedRelease = $PSVersionTable.PSVersion.ToString() | |
if ($installedRelease -eq $latestRelease) { | |
Write-Host "You already have the latest version installed (v$installedRelease)" | |
Write-Host "You can run Install-Powershell <version> to force-install a specific version" | |
} else { | |
# Download the installer and run it | |
Install-Powershell $latestRelease | |
} | |
} | |
Export-ModuleMember -Function * |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment