function DownloadPowershell($OUTPUT_FOLDER="C:\pwsh", $ARCH="win-x64") { function EnsurePathIncludes($path) { $currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine") $paths = $currentPath.Split(";") foreach ($p in $paths) { if ($p -like $path) { return } } $newPath = $currentPath + ";$path" [Environment]::SetEnvironmentVariable("Path", $newPath, "Machine") } function GetLatestPowershellDownloadUrl( $RELEASE_URL="https://api.github.com/repos/PowerShell/PowerShell/releases/latest", $arch="win-x64" ) { $data = Invoke-RestMethod -Uri $RELEASE_URL foreach ($url in $data.assets.browser_download_url) { if ($url -like "*$arch.zip") { return $url } } throw "No download URL found for architecture $arch from $RELEASE_URL" } function DownloadFile($url, $outputPath) { $client = New-Object System.Net.WebClient $client.DownloadFile($url, $outputPath) $client.Dispose() } function ExtractZip($zipPath, $extractTo) { Add-Type -Assembly 'System.IO.Compression.FileSystem' [System.IO.Compression.ZipFile]::ExtractToDirectory($zipPath, $extractTo) } # Main logic Write-Host "Getting latest Powershell download URL..." $downloadUrl = GetLatestPowershellDownloadUrl -arch $ARCH $zipFileName = [System.IO.Path]::GetFileName($downloadUrl) $tempZipPath = Join-Path -Path $env:TEMP -ChildPath $zipFileName Write-Host "Downloading $downloadUrl to $tempZipPath..." DownloadFile $downloadUrl $tempZipPath if (Test-Path -Path $OUTPUT_FOLDER) { Write-Host "Output folder $OUTPUT_FOLDER already exists. Removing it..." Remove-Item -Path $OUTPUT_FOLDER -Recurse -Force } Write-Host "Extracting $tempZipPath to $OUTPUT_FOLDER..." ExtractZip $tempZipPath $OUTPUT_FOLDER Write-Host "Adding $OUTPUT_FOLDER to system PATH..." EnsurePathIncludes $OUTPUT_FOLDER } DownloadPowershell