Skip to content

Instantly share code, notes, and snippets.

@BuriedStPatrick
Last active March 17, 2021 20:24
Show Gist options
  • Save BuriedStPatrick/4dc37b65b4a92d3b7467b0a33fcfcad0 to your computer and use it in GitHub Desktop.
Save BuriedStPatrick/4dc37b65b4a92d3b7467b0a33fcfcad0 to your computer and use it in GitHub Desktop.
Update/Install latest Powershell version
# 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
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