Install-StandardApps.ps1

<#PSScriptInfo
.VERSION 1.0.0
.GUID efff0b7c-cef9-5b71-8915-0046cf545660
.AUTHOR Torsten Weise
.COMPANYNAME powerscripting.de
.COPYRIGHT (c) 2026 Torsten Weise. MIT-Lizenz.
.TAGS Powerscripting German Monitoring Report Windows Backup winget Deployment Setup Software PSEdition_Desktop PSEdition_Core
.LICENSEURI https://powerscripting.de/skripte/files/LICENSE.txt
.PROJECTURI https://powerscripting.de/skripte/install-standardapps.html
.ICONURI https://powerscripting.de/assets/icon-192.png
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
Erste Veröffentlichung in der PowerShell Gallery.
.PRIVATEDATA
#>


<#
.SYNOPSIS
    Richtet einen neuen Windows-PC per winget aus einer Konfigurationsdatei ein, mit Logdatei und Fehlerbericht.
 
.DESCRIPTION
    Ein neuer Rechner braucht immer dieselben Programme: Browser, PDF, 7-Zip, Teams, Fernwartung, je nach
    Abteilung noch ein paar mehr. Das Skript installiert sie aus einer JSON-Datei mit winget, unbeaufsichtigt
    und nachvollziehbar:
 
    - Programme stehen mit winget-ID in der Konfiguration, optional mit Profil (z. B. basis, entwicklung),
      Bereich (machine/user), fester Version, eigenen Installer-Argumenten und dem Merkmal "optional".
    - Bereits installierte Programme werden übersprungen (mit -Upgrade stattdessen aktualisiert).
    - Jeder winget-Aufruf landet mit Ausgabe und Exitcode in der Logdatei.
    - Bekannte winget-Fehlercodes werden in Klartext übersetzt. Vorübergehende Fehler (kein Netz,
      andere Installation läuft) werden wiederholt.
    - Am Ende entstehen ein CSV mit dem Ergebnis je Programm und ein Fehlerbericht als Text, den man direkt
      ins Ticket kopieren kann.
 
    Mit -NewConfig schreibt das Skript eine Beispielkonfiguration, die man anpasst.
 
    Exitcode: 0 alles installiert, 1 optionale Programme fehlgeschlagen oder Neustart nötig,
    2 mindestens ein Pflichtprogramm fehlgeschlagen, 3 winget fehlt.
 
.PARAMETER ConfigPath
    Pfad zur JSON-Konfiguration.
 
.PARAMETER ProfileName
    Nur Programme dieser Profile installieren. Programme ohne Profil werden immer installiert.
    Ohne Angabe: alle Programme.
 
.PARAMETER Upgrade
    Bereits installierte Programme aktualisieren statt überspringen.
 
.PARAMETER LogPath
    Ordner für Log, CSV und Fehlerbericht. Standard: C:\ProgramData\Powerscripting\Install-StandardApps.
 
.PARAMETER RetryCount
    Wiederholungen bei vorübergehenden Fehlern. Standard: 2.
 
.PARAMETER NewConfig
    Schreibt eine Beispielkonfiguration an diesen Pfad und beendet sich.
 
.EXAMPLE
    .\Install-StandardApps.ps1 -NewConfig .\standardapps.json
 
    Legt eine Beispielkonfiguration an.
 
.EXAMPLE
    .\Install-StandardApps.ps1 -ConfigPath \\fs01\it$\standardapps.json -ProfileName basis, buchhaltung
 
    Installiert die Basisprogramme und die der Buchhaltung.
 
.EXAMPLE
    .\Install-StandardApps.ps1 -ConfigPath .\standardapps.json -WhatIf
 
    Zeigt, was installiert würde, ohne etwas zu ändern.
 
.NOTES
    Autor: Torsten Weise, powerscripting.de
    Läuft mit Windows PowerShell 5.1 und PowerShell 7 unter Windows 10/11 und Server 2025 mit winget
    (App-Installer). Für Programme mit Bereich "machine" als Administrator starten.
    winget-Fehlercodes: https://github.com/microsoft/winget-cli/blob/master/doc/windows/package-manager/winget/returnCodes.md
#>

[CmdletBinding(SupportsShouldProcess, DefaultParameterSetName = 'Install')]
param(
    [Parameter(Mandatory, ParameterSetName = 'Install')] [string] $ConfigPath,
    [Parameter(ParameterSetName = 'Install')] [string[]] $ProfileName,
    [Parameter(ParameterSetName = 'Install')] [switch] $Upgrade,
    [Parameter(ParameterSetName = 'Install')] [string] $LogPath,
    [Parameter(ParameterSetName = 'Install')] [ValidateRange(0, 5)] [int] $RetryCount = 2,
    [Parameter(Mandatory, ParameterSetName = 'NewConfig')] [string] $NewConfig
)

$ErrorActionPreference = 'Stop'

if ($PSCmdlet.ParameterSetName -eq 'NewConfig') {
    $sample = [ordered]@{
        name     = 'Büro-Standard'
        defaults = [ordered]@{ scope = 'machine'; source = 'winget' }
        apps     = @(
            [ordered]@{ id = 'Mozilla.Firefox.de'; name = 'Firefox' }
            [ordered]@{ id = '7zip.7zip'; name = '7-Zip' }
            [ordered]@{ id = 'Adobe.Acrobat.Reader.64-bit'; name = 'Acrobat Reader' }
            [ordered]@{ id = 'Microsoft.Teams'; name = 'Teams'; scope = 'user' }
            [ordered]@{ id = 'Notepad++.Notepad++'; name = 'Notepad++'; profiles = @('it', 'entwicklung') }
            [ordered]@{ id = 'Microsoft.VisualStudioCode'; name = 'VS Code'; profiles = @('entwicklung'); override = '/VERYSILENT /MERGETASKS=!runcode' }
            [ordered]@{ id = 'Git.Git'; name = 'Git'; profiles = @('entwicklung') }
            [ordered]@{ id = 'VideoLAN.VLC'; name = 'VLC'; optional = $true }
        )
    }
    $sample | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $NewConfig -Encoding UTF8
    Write-Host "Beispielkonfiguration geschrieben: $NewConfig"
    exit 0
}

# Bekannte winget-Rückgabecodes (Auszug)
$Codes = @{
    '0x8A15002B' = @('Aktuell', 'Keine neuere Version verfügbar', $false)
    '0x8A150061' = @('Bereits vorhanden', 'Paket ist bereits installiert', $false)
    '0x8A15010D' = @('Bereits vorhanden', 'Eine andere Version ist bereits installiert', $false)
    '0x8A150014' = @('Fehler', 'Paket-ID nicht gefunden. ID mit "winget search" prüfen', $false)
    '0x8A150101' = @('Fehler', 'Programm läuft gerade und blockiert die Installation', $true)
    '0x8A150102' = @('Fehler', 'Eine andere Installation läuft gerade', $true)
    '0x8A150105' = @('Fehler', 'Datenträger voll', $false)
    '0x8A150107' = @('Fehler', 'Keine Netzwerkverbindung', $true)
    '0x8A150109' = @('Neustart nötig', 'Installation wird nach dem Neustart abgeschlossen', $false)
    '0x8A15010A' = @('Neustart nötig', 'Neustart vor der Installation nötig', $false)
    '0x8A15010C' = @('Fehler', 'Installation abgebrochen', $false)
    '0x8A15010F' = @('Fehler', 'Durch Richtlinie blockiert', $false)
    '0x00000BC2' = @('Neustart nötig', 'Installiert, Neustart nötig (3010)', $false)
    '0x00000669' = @('Neustart nötig', 'Installiert, Neustart eingeleitet (1641)', $false)
}

function Get-Hex([int] $Code) { return '0x{0:X8}' -f $Code }

# ---------- Vorbereitung ----------

if (-not $LogPath) {
    $base = if ($env:ProgramData) { $env:ProgramData } else { [IO.Path]::GetTempPath() }
    $LogPath = Join-Path $base 'Powerscripting\Install-StandardApps'
}
if (-not (Test-Path -LiteralPath $LogPath)) { New-Item -ItemType Directory -Path $LogPath -Force -WhatIf:$false | Out-Null }
$computer = if ($env:COMPUTERNAME) { $env:COMPUTERNAME } else { [Environment]::MachineName }
$stamp = Get-Date -Format 'yyyy-MM-dd_HHmmss'
$logFile = Join-Path $LogPath "Install-StandardApps_${computer}_$stamp.log"

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

$cfg = Get-Content -LiteralPath $ConfigPath -Raw -Encoding UTF8 | ConvertFrom-Json
if (-not $cfg.apps) { throw "$ConfigPath enthält keine Programme (apps)." }
Write-InstallLog "Konfiguration: $ConfigPath ($($cfg.name)), Rechner $computer"

if (-not (Get-Command winget -ErrorAction SilentlyContinue)) {
    Write-InstallLog 'winget wurde nicht gefunden. App-Installer aus dem Microsoft Store installieren oder aktualisieren.' 'Red'
    exit 3
}

if ($env:OS -eq 'Windows_NT') {
    $id = [Security.Principal.WindowsIdentity]::GetCurrent()
    $admin = ([Security.Principal.WindowsPrincipal]$id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    if (-not $admin) { Write-InstallLog 'Hinweis: nicht als Administrator gestartet, Programme mit Bereich "machine" können scheitern.' 'Yellow' }
}

$defScope  = if ($cfg.defaults -and $cfg.defaults.scope) { $cfg.defaults.scope } else { '' }
$defSource = if ($cfg.defaults -and $cfg.defaults.source) { $cfg.defaults.source } else { 'winget' }

$apps = @(foreach ($a in $cfg.apps) {
    $p = @($a.profiles | Where-Object { $_ })
    if ($ProfileName -and $p.Count -gt 0 -and -not ($p | Where-Object { $ProfileName -contains $_ })) { continue }
    $a
})
Write-InstallLog "$($apps.Count) von $(@($cfg.apps).Count) Programmen ausgewählt$(if ($ProfileName) { " (Profile: $($ProfileName -join ', '))" })"

function Invoke-Winget([string[]] $Arguments) {
    Add-Content -LiteralPath $logFile -Value (" > winget " + ($Arguments -join ' ')) -Encoding UTF8 -WhatIf:$false
    $out = & winget @Arguments 2>&1
    $code = $LASTEXITCODE
    if ($null -eq $code) { $code = 0 }
    $text = (@($out) | ForEach-Object { "$_" } | Where-Object { $_ -and $_ -notmatch '^[\s\-\\|/]+$' }) -join [Environment]::NewLine
    if ($text) { Add-Content -LiteralPath $logFile -Value (($text -split "`r?`n" | ForEach-Object { " $_" }) -join [Environment]::NewLine) -Encoding UTF8 -WhatIf:$false }
    return [pscustomobject]@{ Code = [int]$code; Output = $text }
}

if ($PSCmdlet.ShouldProcess('winget-Quellen', 'aktualisieren')) {
    [void](Invoke-Winget @('source', 'update', '--disable-interactivity'))
}

# ---------- Installation ----------

$results = New-Object System.Collections.Generic.List[object]
foreach ($a in $apps) {
    $appId  = "$($a.id)"
    $name   = if ($a.name) { "$($a.name)" } else { $appId }
    $scope  = if ($a.scope) { "$($a.scope)" } else { $defScope }
    $source = if ($a.source) { "$($a.source)" } else { $defSource }
    $optional = [bool]$a.optional
    $sw = [Diagnostics.Stopwatch]::StartNew()

    $listed = Invoke-Winget @('list', '--id', $appId, '--exact', '--source', $source, '--accept-source-agreements', '--disable-interactivity')
    $installed = $listed.Code -eq 0
    $verb = 'install'
    if ($installed) {
        if (-not $Upgrade) {
            Write-InstallLog "= $name ist bereits installiert" 'DarkGray'
            $results.Add([pscustomobject]@{ Id = $appId; Name = $name; Status = 'Bereits vorhanden'; ExitCode = 0; Hex = '0x00000000'; Message = ''; Optional = $optional; Seconds = 0 })
            continue
        }
        $verb = 'upgrade'
    }

    $args2 = @($verb, '--id', $appId, '--exact', '--source', $source, '--silent', '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity')
    if ($scope -and $verb -eq 'install') { $args2 += @('--scope', $scope) }
    if ($a.version) { $args2 += @('--version', "$($a.version)") }
    if ($a.override) { $args2 += @('--override', "$($a.override)") }
    if ($a.custom) { $args2 += @('--custom', "$($a.custom)") }

    if (-not $PSCmdlet.ShouldProcess($name, "winget $verb")) {
        $results.Add([pscustomobject]@{ Id = $appId; Name = $name; Status = 'Übersprungen (WhatIf)'; ExitCode = 0; Hex = ''; Message = ($args2 -join ' '); Optional = $optional; Seconds = 0 })
        continue
    }

    $try = 0
    do {
        $try++
        Write-InstallLog "+ $name ($appId) $(if ($verb -eq 'upgrade') { 'aktualisieren' } else { 'installieren' })$(if ($try -gt 1) { ", Versuch $try" }) ..."
        $r = Invoke-Winget $args2
        $hex = Get-Hex $r.Code
        $known = $Codes[$hex]
        $retry = $known -and $known[2] -and $try -le $RetryCount
        if ($retry) { Start-Sleep -Seconds ([math]::Min(30, 10 * $try)) }
    } while ($retry)

    if ($r.Code -eq 0) { $status = 'Installiert'; $msg = '' }
    elseif ($known) { $status = $known[0]; $msg = $known[1] }
    else {
        $status = 'Fehler'
        $last = @($r.Output -split "`r?`n" | Where-Object { $_.Trim() }) | Select-Object -Last 1
        $msg = "Unbekannter Code $hex. $last".Trim()
    }
    if ($verb -eq 'upgrade' -and $status -eq 'Installiert') { $status = 'Aktualisiert' }
    $color = switch ($status) { 'Fehler' { if ($optional) { 'Yellow' } else { 'Red' } } 'Neustart nötig' { 'Yellow' } default { 'Green' } }
    Write-InstallLog (" -> {0}{1} [{2}]" -f $status, $(if ($msg) { ": $msg" }), $hex) $color
    $results.Add([pscustomobject]@{ Id = $appId; Name = $name; Status = $status; ExitCode = $r.Code; Hex = $hex; Message = $msg; Optional = $optional; Seconds = [math]::Round($sw.Elapsed.TotalSeconds) })
}

# ---------- Bericht ----------

$csvFile = Join-Path $LogPath "Install-StandardApps_${computer}_$stamp.csv"
$results | Export-Csv -LiteralPath $csvFile -Delimiter ';' -NoTypeInformation -Encoding UTF8 -WhatIf:$false

$failed   = @($results | Where-Object { $_.Status -eq 'Fehler' -and -not $_.Optional })
$optFail  = @($results | Where-Object { $_.Status -eq 'Fehler' -and $_.Optional })
$reboot   = @($results | Where-Object Status -eq 'Neustart nötig')
$ok       = @($results | Where-Object { $_.Status -in @('Installiert', 'Aktualisiert', 'Bereits vorhanden', 'Aktuell') })

$report = Join-Path $LogPath "Fehlerbericht_${computer}_$stamp.txt"
$lines = @(
    "Einrichtung $computer am $(Get-Date -Format 'dd.MM.yyyy HH:mm')"
    "Konfiguration: $ConfigPath$(if ($ProfileName) { " | Profile: $($ProfileName -join ', ')" })"
    "Benutzer: $env:USERNAME"
    ''
    "In Ordnung: $($ok.Count) | Fehler: $($failed.Count) | Fehler optional: $($optFail.Count) | Neustart nötig: $($reboot.Count)"
    ''
)
if ($failed.Count + $optFail.Count + $reboot.Count -eq 0) { $lines += 'Keine Fehler.' }
foreach ($x in @($failed) + @($optFail) + @($reboot)) {
    $lines += "- $($x.Name) ($($x.Id)): $($x.Status)$(if ($x.Optional) { ' (optional)' }) [$($x.Hex)] $($x.Message)"
}
$lines += @('', "Log: $logFile", "Ergebnis: $csvFile")
$lines | Set-Content -LiteralPath $report -Encoding UTF8 -WhatIf:$false

Write-InstallLog ("Fertig: {0} in Ordnung, {1} Fehler, {2} optional fehlgeschlagen, {3} mit Neustart" -f $ok.Count, $failed.Count, $optFail.Count, $reboot.Count) $(if ($failed) { 'Red' } elseif ($optFail -or $reboot) { 'Yellow' } else { 'Green' })
Write-InstallLog "Fehlerbericht: $report"
$results

if ($failed) { exit 2 } elseif ($optFail -or $reboot) { exit 1 } else { exit 0 }