The Ops Community ⚙️

Kai Walter
Kai Walter

Posted on

Install WinGet latest release with PowerShell in one go

I am gradually shifting (semi-)automated installations from Chocolatey / choco to Windows Package Manager / winget.

When I hit older machines, which do no yet have WinGet installed, I use a script like this to get it installed from the latest release available on GitHub

$ErrorActionPreference = 'Stop'

$r = Invoke-RestMethod -Method Get -Uri https://api.github.com/repos/microsoft/winget-cli/releases/latest

$r.assets | ? { $_.name -match "\.msixbundle$" } | % {
    $downloadedFile = Join-Path $env:Temp $_.name
    if (Test-Path $downloadedFile) {
        Remove-Item $downloadedFile -Force
    }
    Write-Host "download from" $_.browser_download_url "to" $downloadedFile
    Invoke-WebRequest -Uri $_.browser_download_url -OutFile $downloadedFile
    if ($PSVersionTable.PSVersion.PSEdition -eq "Desktop") {
        Add-AppxPackage -Path $downloadedFile -ForceUpdateFromAnyVersion
    }
    elseif ($PSVersionTable.OS -match "Windows") {
        Invoke-Item $downloadedFile
    } else {
        throw "OS is not supported"
    }
    Remove-Item $downloadedFile -Force
}
Enter fullscreen mode Exit fullscreen mode

As PowerShell 5.x still has the Add-AppxPackage command, one can even force the installation when running with the "old" version. With PowerShell Core one is reduced to just invoking the item / .msixbundle file.

This script also nicely shows how to walk through assets of a GitHub release when one knows user/repository like microsoft/winget-cli.

Top comments (0)