# Shared helper: ensures winget is accessible before use. # Dot-source this script and call Initialize-Winget at startup. # Repair operations require administrator rights. function Initialize-Winget { if (Get-Command winget -ErrorAction SilentlyContinue) { return } Write-Host "winget not found in PATH. Attempting repair..." -ForegroundColor Yellow # Refresh PATH from registry in case a recent install is not yet visible $MachinePath = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") $UserPath = [System.Environment]::GetEnvironmentVariable("PATH", "User") $env:PATH = $MachinePath + ";" + $UserPath if (Get-Command winget -ErrorAction SilentlyContinue) { Write-Host "winget available after PATH refresh." -ForegroundColor Green return } # Try to re-register the installed App Installer package $AppInstaller = Get-AppxPackage -Name "Microsoft.DesktopAppInstaller" -ErrorAction SilentlyContinue if (-not $AppInstaller) { $AppInstaller = Get-AppxPackage -AllUsers -Name "Microsoft.DesktopAppInstaller" -ErrorAction SilentlyContinue } if ($AppInstaller) { Write-Host "Re-registering App Installer..." -ForegroundColor Yellow try { $Manifest = Join-Path $AppInstaller.InstallLocation "AppxManifest.xml" Add-AppxPackage -DisableDevelopmentMode -Register $Manifest -ErrorAction Stop $env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "User") if (Get-Command winget -ErrorAction SilentlyContinue) { Write-Host "winget repaired." -ForegroundColor Green return } } catch { Write-Warning "Re-registration failed: $_" } } # Try to reinstall from the provisioned (staged) package on this machine $StagedPackage = Get-AppxProvisionedPackage -Online -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -eq "Microsoft.DesktopAppInstaller" } | Select-Object -First 1 if ($StagedPackage) { Write-Host "Installing App Installer from provisioned package..." -ForegroundColor Yellow try { Add-AppxPackage -Path $StagedPackage.PackagePath -ErrorAction Stop $env:PATH = [System.Environment]::GetEnvironmentVariable("PATH", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("PATH", "User") if (Get-Command winget -ErrorAction SilentlyContinue) { Write-Host "winget installed." -ForegroundColor Green return } } catch { Write-Warning "Installation from provisioned package failed: $_" } } Write-Error ("winget is not available and could not be repaired automatically.`n" + "Install App Installer from the Microsoft Store: " + "ms-windows-store://pdp/?productid=9nblggh4nns1") exit 1 }