Install PowerShell with PowerShell

I’m trying to get better about using the new versions of PowerShell (7.x) instead of Windows PowerShell (5.x), but I find that I forget to install it on some machines. To make that easier, I wrote myself a script (in PowerShell) to install PowerShell. I know – don’t judge me. This is the script.

https://github.com/PowerShell/PowerShell/releases/latest
#Requires -RunAsAdministrator

# Modern websites require TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$Uri = "https://github.com/PowerShell/PowerShell/releases/"
$RawPageContents = Invoke-RestMethod -Uri $Uri
$Versions = [regex]::Matches($RawPageContents, '/PowerShell/PowerShell/releases/download/v\d*\.\d*\.\d*/PowerShell-(?<version>\d*\.\d*\.\d*)-win-x64\.msi') | Select-Object -Property @{ Name = "Version"; Expression = { [Version]( $_.Groups[1].Value ) } }, @{ Name = "URL"; Expression = { $_.Value } }
# Get only the most recent version (by version number)
$VersionToDownload = $Versions | Sort-Object -Property Version -Descending | Select-Object -First 1

# Find the server name based on the original URI
$BasePath = [System.Uri]( $Uri ) | Select-Object -Property @{ Name = 'ServerName'; Expression = { $_.Scheme + '://' + $_.Host } } | Select-Object -ExpandProperty ServerName

# Build the full URL for download
$DownloadUrl = $BasePath + $VersionToDownload.URL

# Download the file to temp
Invoke-WebRequest -Uri $DownloadUrl -OutFile "$env:temp\$( $DownloadUrl.Split('/')[-1] )"

# Install the program without user interaction (only show progress bar)
Start-Process -FilePath "C:\WINDOWS\system32\msiexec.exe" -ArgumentList "/package", "$env:temp\$( $DownloadUrl.Split('/')[-1] )", "/passive" -Wait

The script will search on the GitHub releases page for matching (x64) msi files and then download and install the most recent (by version number, not date) one. It’s simple, but effective.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.