@@ -233,9 +233,32 @@ runs:
233233 Write-Host "Starting installation of PowerShell [$($env:REQUESTED_VERSION)]..."
234234
235235 if ($isDowngrade) {
236- # For downgrades, use force reinstall to overwrite the existing version
237- Write-Host "Using force reinstall for downgrade scenario..."
238- Start-Process msiexec.exe -ArgumentList '/f', $msi, '/quiet', '/norestart', 'REINSTALL=a' -Wait
236+ # For downgrades, uninstall the existing version first, then install the new one
237+ Write-Host "Downgrade detected - uninstalling existing PowerShell version first..."
238+
239+ # Find PowerShell installation to uninstall
240+ $uninstallString = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" -ErrorAction SilentlyContinue |
241+ Where-Object { $_.DisplayName -like "*PowerShell*" -and $_.Publisher -eq "Microsoft Corporation" } |
242+ Select-Object -First 1 -ExpandProperty UninstallString
243+
244+ if ($uninstallString) {
245+ Write-Host "Found existing PowerShell installation, uninstalling..."
246+ # Extract the product code from the uninstall string
247+ if ($uninstallString -match '{[0-9A-F-]+}') {
248+ $productCode = $matches[0]
249+ Write-Host "Uninstalling PowerShell with product code: $productCode"
250+ Start-Process msiexec.exe -ArgumentList '/x', $productCode, '/quiet', '/norestart' -Wait
251+ Write-Host "Uninstall completed"
252+ } else {
253+ Write-Host "Warning: Could not extract product code from uninstall string: $uninstallString"
254+ }
255+ } else {
256+ Write-Host "Warning: Could not find PowerShell installation to uninstall"
257+ }
258+
259+ # Now install the new version
260+ Write-Host "Installing PowerShell [$($env:REQUESTED_VERSION)]..."
261+ Start-Process msiexec.exe -ArgumentList '/i', $msi, '/quiet', '/norestart' -Wait
239262 } else {
240263 # For upgrades or fresh installs, use regular install
241264 Start-Process msiexec.exe -ArgumentList '/i', $msi, '/quiet', '/norestart' -Wait
0 commit comments