Search code examples
powershellintunewinget

PowerShell - WinGet - Compare Available Package Version to Currently installed


Currently working with WinGet to improve application deployment lifecycle within Intune. I am looking at deploying a detection script that checks for the installed version daily, then triggers the remediation if there is an available update.

Doing something as simple as:

winget list --name 7-Zip

will return as follows:

Name              Id        Version Available Source
----------------------------------------------------
7-Zip 19.00 (x64) 7zip.7zip 19.00   22.01     winget

Within Powershell, is there a way we can check and compare the Available "column" to the Version "column", and return an exit 0 or exit 1?

Thanks in advance


Solution

  • If all you need to know is whether or not an upgrade is available, to be reflected in the script's exit code:

    The following reports exit code 1 if an upgrade is available, and 0 otherwise, relying on an Available column header only being present if an upgrade is available:

    exit [int] (winget list --name 7-Zip | Select-String '\bVersion\s+Available\b' -Quiet)
    

    If you also want to report the installed vs. the latest available version, more work is needed:

    $name = '7-Zip'
    $lines = winget list --name $name
    if ($lines -match '\bVersion\s+Available\b') {
      $verinstalled, $verAvailable = (-split $lines[-1])[-3,-2]
      [pscustomobject] @{
        Name = $name
        InstalledVersion = [version] $verInstalled
        AvailableVersion = [version] $verAvailable
      }
      exit 1
    } else {
      Write-Verbose -Verbose "No upgrade for $name available."
      exit 0
    }
    

    The above outputs something like the following if an upgrade is available; the exit code is set as in the first command:

    Name    InstalledVersion AvailableVersion
    ----    ---------------- ----------------
    7-Zip   9.0.30729.4148   9.0.30729.6161
    

    Alternatively, if it's acceptable to blindly try to upgrade:

    winget upgrade --name 7-Zip --silent
    # If $LASTEXITCODE contains -1978335189, an upgrade was NOT available.