config-central/src/Packages.psm1

119 lines
6.9 KiB
PowerShell

Set-StrictMode -Version Latest
$script:WingetNoApplicableUpgrade = [uint32]0x8A15002B
function Test-VersionGreaterThan {
param([string]$Left, [string]$Right)
$leftVersion = $null
$rightVersion = $null
if ([version]::TryParse($Left, [ref]$leftVersion) -and [version]::TryParse($Right, [ref]$rightVersion)) {
return $leftVersion -gt $rightVersion
}
return [string]::Compare($Left, $Right, [System.StringComparison]::OrdinalIgnoreCase) -gt 0
}
function Invoke-WingetCapture {
param([Parameter(Mandatory)][string[]]$Arguments, [string]$LogPath)
$outputPath = [System.IO.Path]::GetTempFileName()
$errorPath = [System.IO.Path]::GetTempFileName()
try {
$process = Start-Process -FilePath 'winget.exe' -ArgumentList $Arguments -Wait -PassThru -NoNewWindow -RedirectStandardOutput $outputPath -RedirectStandardError $errorPath
$output = ((Get-Content -LiteralPath $outputPath -Raw -ErrorAction SilentlyContinue), (Get-Content -LiteralPath $errorPath -Raw -ErrorAction SilentlyContinue) -join [Environment]::NewLine).Trim()
if ($LogPath) { $output | Add-Content -LiteralPath $LogPath -Encoding utf8 }
[pscustomobject]@{ exitCode = $process.ExitCode; unsignedExitCode = [uint32]$process.ExitCode; output = $output }
}
finally {
Remove-Item -LiteralPath $outputPath, $errorPath -Force -ErrorAction SilentlyContinue
}
}
function Get-WingetInventory {
if (-not (Get-Command winget.exe -ErrorAction SilentlyContinue)) { throw 'WinGet (winget.exe) is not available.' }
$exportPath = Join-Path ([System.IO.Path]::GetTempPath()) "config-central-$([guid]::NewGuid().ToString('N')).json"
try {
$result = Invoke-WingetCapture -Arguments @('export', '--output', $exportPath, '--include-versions', '--accept-source-agreements', '--disable-interactivity')
if ($result.exitCode -ne 0 -or -not (Test-Path -LiteralPath $exportPath)) {
throw "WinGet inventory export failed ($($result.unsignedExitCode)): $($result.output)"
}
$export = Get-Content -LiteralPath $exportPath -Raw | ConvertFrom-Json -Depth 32
$inventory = [ordered]@{}
foreach ($source in @($export.Sources)) {
foreach ($package in @($source.Packages)) {
$key = "$($source.SourceDetails.Name)/$($package.PackageIdentifier)".ToLowerInvariant()
if ($inventory.Contains($key)) { throw "Ambiguous installed package '$key' in WinGet inventory." }
$inventory[$key] = [pscustomobject]@{
id = [string]$package.PackageIdentifier
source = [string]$source.SourceDetails.Name
version = [string]$package.Version
}
}
}
return $inventory
}
finally { Remove-Item -LiteralPath $exportPath -Force -ErrorAction SilentlyContinue }
}
function Get-PackagePlan {
param([Parameter(Mandatory)]$Packages, [Parameter(Mandatory)]$Inventory)
$plan = [System.Collections.Generic.List[object]]::new()
foreach ($package in @($Packages)) {
$key = "$($package.source)/$($package.id)".ToLowerInvariant()
$installed = if ($Inventory.Contains($key)) { $Inventory[$key] } else { $null }
$versionProperty = $package.PSObject.Properties['version']
$requestedVersion = if ($null -ne $versionProperty) { [string]$versionProperty.Value } else { $null }
if ($null -eq $installed) {
$plan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'Install'; reason = 'Package is absent'; package = $package })
}
elseif ($package.update -eq 'install-only') {
$plan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'None'; reason = "Installed ($($installed.version)); install-only policy"; package = $package })
}
elseif ($requestedVersion) {
if ($installed.version -eq $requestedVersion) {
$plan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'None'; reason = "Pinned version $requestedVersion is installed"; package = $package })
}
elseif (Test-VersionGreaterThan $installed.version $requestedVersion) {
$plan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'Warning'; reason = "Installed $($installed.version) is newer than requested $requestedVersion"; package = $package })
}
else {
$plan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'Install'; reason = "Move $($installed.version) to pinned $requestedVersion"; package = $package })
}
}
else {
$plan.Add([pscustomobject]@{ kind = 'package'; name = $package.id; action = 'Upgrade'; reason = "Ask WinGet for an upgrade from $($installed.version)"; package = $package })
}
}
return @($plan)
}
function Invoke-PackageOperation {
param([Parameter(Mandatory)]$Operation, [string]$LogPath)
if ($Operation.action -in @('None', 'Warning')) {
return [pscustomobject]@{ name = $Operation.name; status = $Operation.action; exitCode = 0; rebootRequired = $false; message = $Operation.reason }
}
$package = $Operation.package
$verb = if ($Operation.action -eq 'Upgrade') { 'upgrade' } else { 'install' }
$arguments = @($verb, '--id', $package.id, '--exact', '--source', $package.source, '--silent', '--disable-interactivity', '--accept-package-agreements', '--accept-source-agreements')
if ($package.PSObject.Properties['scope']) { $arguments += @('--scope', $package.scope) }
if ($package.PSObject.Properties['version']) { $arguments += @('--version', $package.version) }
$result = Invoke-WingetCapture -Arguments $arguments -LogPath $LogPath
if ($result.unsignedExitCode -eq $script:WingetNoApplicableUpgrade) {
return [pscustomobject]@{ name = $Operation.name; status = 'Unchanged'; exitCode = 0; rebootRequired = $false; message = 'No applicable upgrade' }
}
if ($result.exitCode -in @(3010, 1641)) {
return [pscustomobject]@{ name = $Operation.name; status = 'Succeeded'; exitCode = $result.exitCode; rebootRequired = $true; message = 'Installed; reboot required' }
}
if ($result.exitCode -ne 0) {
return [pscustomobject]@{ name = $Operation.name; status = 'Failed'; exitCode = $result.unsignedExitCode; rebootRequired = $false; message = $result.output }
}
[pscustomobject]@{ name = $Operation.name; status = 'Succeeded'; exitCode = 0; rebootRequired = $false; message = "$($Operation.action) completed" }
}
function Invoke-PackagePlan {
param([Parameter(Mandatory)]$Plan, [string]$LogPath)
$results = [System.Collections.Generic.List[object]]::new()
foreach ($operation in @($Plan)) { $results.Add((Invoke-PackageOperation -Operation $operation -LogPath $LogPath)) }
return @($results)
}
Export-ModuleMember -Function Get-WingetInventory, Get-PackagePlan, Invoke-PackageOperation, Invoke-PackagePlan