check installed packages, if there'isn't... install.

Matteo Cannoletta 1 Reputation point
2022-02-08T16:14:46.663+00:00

Hi, I would like to check if some packages are already installed, if they are not, i want to install them.
I tried a many things but the "winget list --id" return an object, and i'm not able to figure it out how to manage it.

[int]$isInstalled = -1
Function testPackage ($packageName){
    [string]$test = ""
    try {
        $test = winget list --id $packageName
    } catch {
        $test = ""
    }
    if ($test = "") {
        $isInstalled = 1
    }
    else {
        $isInstalled = 0
    }
    return $isInstalled
}


foreach ($utility in $toInstall) {          #$toInstall is a string array with all the id of the packages that i need
    if (testPackage($utility) -eq 1) {
        write-host "installing $utility..."
        winget install -e --id $utility        
    } 
    else {
        Write-Host "$utility already installed";
    }
}

can anybody help me?
thank you

Windows for business | Windows Server | User experience | PowerShell
Windows for business | Windows Client for IT Pros | User experience | Other
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 36,401 Reputation points
    2022-02-08T16:59:46.883+00:00

    Instead of using winget, can you use Get-Package and Install-Package.

    https://learn.microsoft.com/en-us/powershell/module/packagemanagement/get-package?view=powershell-5.1

    PS C:\Temp> Get-Package | Where-Object -Property Name -like 'google*' | Format-Table -Property Name, Version  
      
    Name          Version       
    ----          -------       
    Google Drive  55.0.3.0      
    Google Chrome 98.0.4758.82  
      
      
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.