Update-WinGetApps.ps1

<#PSScriptInfo
.VERSION 1.0.0
.GUID c140fdcc-9823-5011-b768-b0ce9875c238
.AUTHOR Torsten Weise
.COMPANYNAME powerscripting.de
.COPYRIGHT (c) 2026 Torsten Weise. MIT-Lizenz.
.TAGS Powerscripting German Monitoring Report Windows Backup winget Update Patch PSEdition_Desktop PSEdition_Core
.LICENSEURI https://powerscripting.de/skripte/files/LICENSE.txt
.PROJECTURI https://powerscripting.de/skripte/update-wingetapps.html
.ICONURI https://powerscripting.de/assets/icon-192.png
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
Erste Veröffentlichung in der PowerShell Gallery.
.PRIVATEDATA
#>


<#
.SYNOPSIS
    Aktualisiert alle installierten Programme per winget, mit Ausschlussliste, Protokoll und geplanter Aufgabe.
 
.DESCRIPTION
    Windows Update kümmert sich um Windows, aber nicht um Firefox, 7-Zip, Notepad++, VLC, den PDF-Reader
    oder die Fernwartung. Genau dort liegen viele ausgenutzte Lücken. Das Skript nutzt das offizielle
    PowerShell-Modul Microsoft.WinGet.Client und arbeitet mit Objekten statt mit der Textausgabe von
    winget.exe. Dadurch funktioniert es in jeder Sprache von Windows und auch als Systemkonto (SYSTEM),
    etwa in einer geplanten Aufgabe, aus Intune oder einem RMM-Tool.
 
    Ablauf:
    - Modul Microsoft.WinGet.Client prüfen und bei Bedarf für alle Benutzer installieren.
    - Alle installierten Pakete lesen und die mit verfügbarem Update auswählen.
    - Nur Pakete aus der Quelle "winget" (mit -IncludeStore auch aus dem Microsoft Store).
    - Ausschlüsse aus -Exclude und -ExcludeFile anwenden, Platzhalter wie Adobe.* sind erlaubt.
    - Jedes Paket einzeln und still aktualisieren, Ergebnis protokollieren.
 
    Mit -InstallTask kopiert sich das Skript nach ProgramData und richtet eine geplante Aufgabe ein, die
    täglich als SYSTEM läuft. Ist der Rechner zur geplanten Zeit aus, startet sie beim nächsten Einschalten.
    Mit -RemoveTask wird sie wieder entfernt.
 
    Als SYSTEM sieht winget nur Programme, die für alle Benutzer installiert sind. Programme, die ein
    Benutzer nur für sich unter AppData installiert hat (etwa Zoom, Spotify oder VS Code im
    Benutzer-Installer), aktualisiert das Skript nur, wenn es in der Sitzung dieses Benutzers läuft.
 
    Exitcode: 0 alles aktuell oder aktualisiert, 1 mindestens ein Update fehlgeschlagen,
    2 winget oder das Modul nicht verfügbar.
 
.PARAMETER Exclude
    Paket-IDs, die nicht aktualisiert werden, z. B. 'Mozilla.Firefox.ESR', 'Oracle.JavaRuntimeEnvironment'.
    Platzhalter sind erlaubt: 'Adobe.*'.
 
.PARAMETER ExcludeFile
    Textdatei mit einer Paket-ID pro Zeile, Zeilen mit # sind Kommentare. Gut für zentrale Listen auf
    einer Freigabe oder im Skriptordner.
 
.PARAMETER IncludeStore
    Auch Apps aus der Quelle msstore aktualisieren. Als SYSTEM funktioniert das oft nicht, deshalb aus.
 
.PARAMETER LogPath
    Ordner für die Protokolle. Standard: ProgramData\Powerscripting\WingetUpdate (als SYSTEM oder Admin),
    sonst AppData\Local\Powerscripting\WingetUpdate.
 
.PARAMETER KeepLogDays
    Protokolle, die älter sind, werden gelöscht. Standard: 30.
 
.PARAMETER InstallTask
    Skript nach ProgramData kopieren und eine tägliche geplante Aufgabe als SYSTEM anlegen.
    Ausschlüsse aus -Exclude und -ExcludeFile werden übernommen. Braucht Administratorrechte.
 
.PARAMETER TaskTime
    Uhrzeit der geplanten Aufgabe, Standard 12:30. Die Aufgabe startet mit bis zu 30 Minuten
    Zufallsverzögerung, damit nicht alle Rechner gleichzeitig laden.
 
.PARAMETER RemoveTask
    Geplante Aufgabe und kopiertes Skript entfernen. Die Protokolle bleiben.
 
.EXAMPLE
    .\Update-WinGetApps.ps1 -WhatIf
 
    Zeigt, welche Programme aktualisiert würden, ohne etwas zu ändern.
 
.EXAMPLE
    .\Update-WinGetApps.ps1 -Exclude 'Oracle.JavaRuntimeEnvironment', 'Adobe.*'
 
    Aktualisiert alles außer Java und allen Adobe-Paketen.
 
.EXAMPLE
    .\Update-WinGetApps.ps1 -InstallTask -ExcludeFile 'C:\ProgramData\Powerscripting\WingetUpdate\exclude.txt' -TaskTime '11:45'
 
    Richtet die tägliche Aufgabe um 11:45 Uhr ein, Ausschlüsse kommen aus der Datei.
 
.EXAMPLE
    .\Update-WinGetApps.ps1 -RemoveTask
 
    Entfernt die geplante Aufgabe wieder.
 
.NOTES
    Autor: Torsten Weise, powerscripting.de
    Benötigt: Windows 10 1809 oder neuer, Windows 11 oder Windows Server 2025 mit App Installer (winget),
    Internetzugang zu PowerShell Gallery und den Downloadquellen der Programme.
    Modul: Microsoft.WinGet.Client, wird bei Bedarf automatisch installiert.
    Laufende Programme: Viele Installer schließen das Programm still, ohne zu fragen. Plane die Aufgabe
    deshalb in die Mittagspause oder außerhalb der Arbeitszeit, und schließe Programme aus, bei denen das
    stört.
#>

#Requires -Version 5.1
[CmdletBinding(SupportsShouldProcess)]
param(
    [string[]] $Exclude,
    [string] $ExcludeFile,
    [switch] $IncludeStore,
    [string] $LogPath,
    [ValidateRange(1, 365)] [int] $KeepLogDays = 30,
    [switch] $InstallTask,
    [ValidatePattern('^\d{1,2}:\d{2}$')] [string] $TaskTime = '12:30',
    [switch] $RemoveTask
)

$TaskName   = 'Powerscripting Winget-Update'
$InstallDir = Join-Path $env:ProgramData 'Powerscripting\WingetUpdate'
$identity   = [Security.Principal.WindowsIdentity]::GetCurrent()
$isSystem   = $identity.User.Value -eq 'S-1-5-18'
$isAdmin    = $isSystem -or ([Security.Principal.WindowsPrincipal]$identity).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

# Geplante Aufgabe entfernen
if ($RemoveTask) {
    if (-not $isAdmin) { throw 'Zum Entfernen der Aufgabe als Administrator starten.' }
    if (Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue) {
        Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
        Write-Host "Aufgabe '$TaskName' entfernt."
    }
    Remove-Item (Join-Path $InstallDir 'Update-WinGetApps.ps1') -ErrorAction SilentlyContinue
    exit 0
}

# Geplante Aufgabe einrichten
if ($InstallTask) {
    if (-not $isAdmin) { throw 'Zum Einrichten der Aufgabe als Administrator starten.' }
    New-Item -Path $InstallDir -ItemType Directory -Force | Out-Null
    $target = Join-Path $InstallDir 'Update-WinGetApps.ps1'
    Copy-Item -Path $PSCommandPath -Destination $target -Force

    # -Command statt -File, damit eine Liste bei -Exclude als Liste ankommt und nicht als ein Text
    $call = "& '$target'"
    if ($Exclude)      { $call += ' -Exclude ' + (($Exclude | ForEach-Object { "'" + ($_ -replace "'", "''") + "'" }) -join ',') }
    if ($ExcludeFile)  { $call += " -ExcludeFile '" + ($ExcludeFile -replace "'", "''") + "'" }
    if ($IncludeStore) { $call += ' -IncludeStore' }
    $call += '; exit $LASTEXITCODE'
    $arg = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -Command "' + $call + '"'

    $action    = New-ScheduledTaskAction -Execute "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument $arg
    $trigger   = New-ScheduledTaskTrigger -Daily -At $TaskTime -RandomDelay (New-TimeSpan -Minutes 30)
    $principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest
    $settings  = New-ScheduledTaskSettingsSet -StartWhenAvailable -RunOnlyIfNetworkAvailable `
                    -ExecutionTimeLimit (New-TimeSpan -Hours 2) -MultipleInstances IgnoreNew
    Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Principal $principal -Settings $settings `
        -Description 'Aktualisiert Programme per winget (powerscripting.de)' -Force | Out-Null
    Write-Host "Aufgabe '$TaskName' eingerichtet: täglich um $TaskTime Uhr als SYSTEM, Skript unter $target"
    Write-Host "Test sofort starten: Start-ScheduledTask -TaskName '$TaskName'"
    exit 0
}

# Protokoll
if (-not $LogPath) {
    $LogPath = if ($isAdmin) { $InstallDir } else { Join-Path $env:LOCALAPPDATA 'Powerscripting\WingetUpdate' }
}
New-Item -Path $LogPath -ItemType Directory -Force | Out-Null
$logFile = Join-Path $LogPath ("WingetUpdate_{0:yyyy-MM-dd_HHmm}.log" -f (Get-Date))
Get-ChildItem -Path $LogPath -Filter 'WingetUpdate_*.log' -ErrorAction SilentlyContinue |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-$KeepLogDays) } | Remove-Item -ErrorAction SilentlyContinue

function Write-UpdateLog([string] $Text, [string] $Color = 'Gray') {
    $line = '{0:yyyy-MM-dd HH:mm:ss} {1}' -f (Get-Date), $Text
    Add-Content -Path $logFile -Value $line -Encoding UTF8
    Write-Host $line -ForegroundColor $Color
}

Write-UpdateLog ("Start als {0}{1}" -f $identity.Name, $(if ($isSystem) { ' (SYSTEM)' } elseif ($isAdmin) { ' (Administrator)' } else { '' }))

# Modul Microsoft.WinGet.Client bereitstellen
if (-not (Get-Module -ListAvailable -Name Microsoft.WinGet.Client)) {
    Write-UpdateLog 'Modul Microsoft.WinGet.Client fehlt, wird installiert'
    try {
        [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
        $scope = if ($isAdmin) { 'AllUsers' } else { 'CurrentUser' }
        if (-not (Get-PackageProvider -ListAvailable -Name NuGet -ErrorAction SilentlyContinue)) {
            Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope $scope | Out-Null
        }
        Install-Module -Name Microsoft.WinGet.Client -Scope $scope -Force -AllowClobber -Repository PSGallery -ErrorAction Stop
    }
    catch {
        Write-UpdateLog "Modul konnte nicht installiert werden: $($_.Exception.Message)" 'Red'
        exit 2
    }
}
Import-Module Microsoft.WinGet.Client -ErrorAction Stop

try {
    $ver = Get-WinGetVersion -ErrorAction Stop
    Write-UpdateLog "winget $ver"
}
catch {
    Write-UpdateLog "winget ist nicht verfügbar: $($_.Exception.Message). Abhilfe: Repair-WinGetPackageManager -AllUsers" 'Red'
    exit 2
}

# Ausschlüsse zusammenstellen
$excl = @($Exclude)
if ($ExcludeFile) {
    if (Test-Path $ExcludeFile) {
        $excl += Get-Content -Path $ExcludeFile | ForEach-Object { $_.Trim() } | Where-Object { $_ -and -not $_.StartsWith('#') }
    } else {
        Write-UpdateLog "Ausschlussdatei $ExcludeFile nicht gefunden, es gelten nur -Exclude-Einträge" 'Yellow'
    }
}
$excl = @($excl | Where-Object { $_ })
if ($excl) { Write-UpdateLog "Ausgeschlossen: $($excl -join ', ')" }

# Pakete mit Update suchen
try {
    $all = @(Get-WinGetPackage -ErrorAction Stop)
}
catch {
    Write-UpdateLog "Paketliste nicht lesbar: $($_.Exception.Message)" 'Red'
    exit 2
}
$sources = if ($IncludeStore) { @('winget', 'msstore') } else { @('winget') }
$candidates = @($all | Where-Object { $_.IsUpdateAvailable -and $_.Source -in $sources })
$todo = @($candidates | Where-Object { $id = $_.Id; -not ($excl | Where-Object { $id -like $_ }) })
$skipped = $candidates.Count - $todo.Count
Write-UpdateLog ("{0} Pakete installiert, {1} mit Update, davon {2} ausgeschlossen" -f $all.Count, $candidates.Count, $skipped)

$results = [System.Collections.Generic.List[object]]::new()
foreach ($p in $todo) {
    $from = $p.InstalledVersion
    $to   = @($p.AvailableVersions)[0]
    if (-not $PSCmdlet.ShouldProcess("$($p.Name) ($($p.Id)) $from -> $to", 'Aktualisieren')) { continue }

    Write-UpdateLog "Aktualisiere $($p.Name) ($($p.Id)) $from -> $to"
    $status = ''; $reboot = $false; $code = ''
    try {
        $r = Update-WinGetPackage -Id $p.Id -Source $p.Source -MatchOption Equals -Mode Silent -ErrorAction Stop
        $status = [string]$r.Status
        $reboot = [bool]$r.RebootRequired
        if ($status -ne 'Ok') { $code = "Installer $($r.InstallerErrorCode), erweitert $($r.ExtendedErrorCode)" }
    }
    catch {
        $status = 'Fehler'
        $code = $_.Exception.Message
    }
    $color = if ($status -eq 'Ok') { 'Green' } else { 'Red' }
    Write-UpdateLog (" -> {0}{1}{2}" -f $status, $(if ($reboot) { ', Neustart nötig' } else { '' }), $(if ($code) { ", $code" } else { '' })) $color

    $results.Add([pscustomobject]@{
        Name      = $p.Name
        Id        = $p.Id
        Von       = $from
        Auf       = $to
        Ergebnis  = $status
        Neustart  = if ($reboot) { 'Ja' } else { 'Nein' }
        Details   = $code
    })
}

$results

$ok     = @($results | Where-Object Ergebnis -eq 'Ok').Count
$failed = @($results | Where-Object Ergebnis -ne 'Ok').Count
$reboot = @($results | Where-Object Neustart -eq 'Ja').Count
Write-UpdateLog ("Fertig: {0} aktualisiert, {1} fehlgeschlagen, {2} ausgeschlossen, Neustart nötig bei {3}" -f $ok, $failed, $skipped, $reboot) $(if ($failed) { 'Yellow' } else { 'Green' })
Write-UpdateLog "Protokoll: $logFile"

if ($failed) { exit 1 } else { exit 0 }