Invoke-AutopilotFailedAppRetry.ps1

<#PSScriptInfo
 
.VERSION 1.0.2
 
.GUID 6f3c9a1e-4b2d-4e8a-9c7f-2a5d8e1b3c40
 
.AUTHOR Wolfgang Bäck
 
.COMPANYNAME CARECON GmbH
 
.COPYRIGHT (c) 2026 Wolfgang Bäck. All rights reserved.
 
.TAGS Intune Autopilot ESP OOBE Win32 IME Retry GRS Apps Failed
 
.RELEASENOTES
1.0.2 (2026-12-04) Wolfgang Bäck: Lists required apps that are assigned but not yet installed in gray with their assignment time. Saves the script as UTF-8 with BOM so Windows PowerShell 5.1 in OOBE shows non-ASCII characters correctly.
1.0.1 (2026-12-04) Wolfgang Bäck: Logs the real install time from IME GRS values, sorted by install time. Adds -TimeZone for displayed times. Shows app names in the retry selection. Logs the version only at startup. No WhatIf output for log writes.
1.0.0 (2026-12-04) Wolfgang Bäck: Initial release. Lists failed Win32 apps with names, clears IME state and GRS entries, restarts IME, triggers MDM sync, optional reboot. Supports -Verbose, -Debug, -WhatIf, -Force.
 
#>


#Requires -RunAsAdministrator

<#
.SYNOPSIS
Retries failed Intune Win32 app installations during Autopilot OOBE/ESP by clearing the IME failure state and GRS cooldown.
 
.DESCRIPTION
Invoke-AutopilotFailedAppRetry reports the latest installation outcome for each Win32 app found in the Intune Management Extension (IME) logs, oldest result first. Installed apps are shown in green, failed apps in red, and required apps that are assigned but not yet installed in gray with their assignment time. By default, only failed apps are selected for retry; -AppIds explicitly selects the apps. The script asks for confirmation unless -Force or -WhatIf is specified.
  1. Exports the IME Win32Apps registry tree to a .reg backup before reporting and prompting.
  2. Stops the IME service after confirmation.
  3. Removes the app state and matching GRS (Global Re-evaluation Schedule) entries.
  4. Starts the IME service so it re-evaluates the apps.
  5. Triggers an MDM sync so the device refreshes its app list (unless -NoSync).
  6. Optionally reboots the device (-Reboot).
 
All output files are written to %windir%\Temp:
  IME-Retry-<timestamp>.log run log (more detail with -Debug)
  IME-Retry-Win32Apps-backup-<timestamp>.reg registry backup, taken before any change
  IME-Retry-transcript-<timestamp>.txt full console transcript (only with -Debug)
 
Intended for use in OOBE/ESP (Shift + F10). Registry layout, GRS hash format and log patterns are heuristics. Test on a VM first.
 
.PARAMETER AppIds
Optional. One or more Win32 app GUIDs to reset. If omitted, failed apps are detected from the IME logs.
 
.PARAMETER Force
Skips the confirmation prompt and resets the listed apps directly.
 
.PARAMETER Reboot
Reboots the device 15 seconds after the script finishes.
 
.PARAMETER NoSync
Skips the MDM sync task that refreshes the app list.
 
.PARAMETER TimeZone
Windows time zone ID used for all displayed times, for example 'W. Europe Standard Time'. Defaults to the device's time zone, which during OOBE may still be the image default rather than the user's. List IDs with Get-TimeZone -ListAvailable.
 
.EXAMPLE
.\Invoke-AutopilotFailedAppRetry.ps1 -WhatIf -TimeZone 'W. Europe Standard Time'
Reports installation results with times shown in Central European time, regardless of the device's current time zone.
 
.EXAMPLE
.\Invoke-AutopilotFailedAppRetry.ps1 -WhatIf
Reports installation results and previews the retry without changing app state. The run log and any registry export are still written.
 
.EXAMPLE
.\Invoke-AutopilotFailedAppRetry.ps1 -Reboot
Lists the failed apps, asks for confirmation, resets them, and reboots.
 
.EXAMPLE
.\Invoke-AutopilotFailedAppRetry.ps1 -Force -Debug
Resets all detected failed apps without prompting and writes a detailed debug log and transcript.
 
.EXAMPLE
.\Invoke-AutopilotFailedAppRetry.ps1 -AppIds 1234abcd-0000-4000-8000-000000000000 -Verbose
Resets one specific app with verbose console output.
 
.NOTES
Author: Wolfgang Bäck
Company: CARECON GmbH
Version: 1.0.2
 
Version history:
Version Date Author Change
1.0.0 2026-12-04 Wolfgang Bäck Initial release
1.0.1 2026-12-04 Wolfgang Bäck Real install times (GRS), sorted by install time, -TimeZone, app names in retry selection
1.0.2 2026-12-04 Wolfgang Bäck Not-yet-installed assigned apps in gray, UTF-8 BOM for Windows PowerShell 5.1
 
Requires: Windows 10/11, PowerShell 5.1 or later, local administrator rights.
 
.LINK
https://github.com/microsoft/Intune-PowerShell-SDK
#>


[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [string[]]$AppIds,       # Optional. If empty, failed apps are detected from the IME logs.
    [switch]$Force,          # Skip the confirmation prompt.
    [switch]$Reboot,         # Reboot at the end.
    [switch]$NoSync,         # Skip the MDM sync (app list refresh).
    [ValidateScript({ [TimeZoneInfo]::FindSystemTimeZoneById($_) })]
    [string]$TimeZone        # Windows time zone ID for displayed times. Default: the device's time zone.
)
# -Verbose and -Debug are built-in common parameters of CmdletBinding. Do not declare them again.

$ScriptName    = 'Invoke-AutopilotFailedAppRetry'
$ScriptVersion = '1.0.2'

$ErrorActionPreference = 'Stop'
if ($PSBoundParameters.ContainsKey('Debug'))   { $DebugPreference   = 'Continue' }  # no "Continue? [Y/N]" prompts
if ($PSBoundParameters.ContainsKey('Verbose')) { $VerbosePreference = 'Continue' }
$DebugMode = ($DebugPreference -eq 'Continue')

$ImeRegPath = 'HKLM\SOFTWARE\Microsoft\IntuneManagementExtension\Win32Apps'
$ImeBase    = 'HKLM:\SOFTWARE\Microsoft\IntuneManagementExtension\Win32Apps'
$LogDir     = Join-Path $env:ProgramData 'Microsoft\IntuneManagementExtension\Logs'
$OutDir     = Join-Path $env:windir 'Temp'
$Stamp      = Get-Date -Format 'yyyyMMdd-HHmmss'
$OutLog     = Join-Path $OutDir "IME-Retry-$Stamp.log"
$BackupFile = Join-Path $OutDir "IME-Retry-Win32Apps-backup-$Stamp.reg"
$TranscriptFile = Join-Path $OutDir "IME-Retry-transcript-$Stamp.txt"
$GuidRx     = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
$HashRx     = '\b[0-9A-Fa-f]{32,64}\b'
$DisplayTimeZone = if ($TimeZone) { [TimeZoneInfo]::FindSystemTimeZoneById($TimeZone) } else { [TimeZoneInfo]::Local }
$script:Errors = 0

if (-not (Test-Path -LiteralPath $OutDir -PathType Container)) {
    New-Item -ItemType Directory -Path $OutDir -Force -WhatIf:$false -Confirm:$false | Out-Null
}

function Write-Log {
    param(
        [string]$Message,
        [ValidateSet('INFO', 'WARN', 'ERROR', 'VERBOSE', 'DEBUG', 'INSTALLED', 'FAILED', 'PENDING')][string]$Level = 'INFO'
    )
    if ($Level -eq 'DEBUG' -and -not $DebugMode) { return }   # DEBUG lines only with -Debug
    $zone = if ($DisplayTimeZone) { $DisplayTimeZone } else { [TimeZoneInfo]::Local }
    $now = [TimeZoneInfo]::ConvertTimeFromUtc([datetime]::UtcNow, $zone)
    $line = '{0} [{1}] {2}' -f $now.ToString('yyyy-MM-dd HH:mm:ss.fff'), $Level, $Message
    [System.IO.File]::AppendAllText($OutLog, $line + [Environment]::NewLine, [Text.Encoding]::UTF8)
    switch ($Level) {
        'WARN'      { Write-Host $line -ForegroundColor Yellow }
        'ERROR'     { Write-Host $line -ForegroundColor Red }
        'FAILED'    { Write-Host $line -ForegroundColor Red }
        'INSTALLED' { Write-Host $line -ForegroundColor Green }
        'PENDING'   { Write-Host $line -ForegroundColor DarkGray }
        'VERBOSE'   { Write-Verbose $line }
        'DEBUG'     { Write-Debug $line }
        default     { Write-Host $line }
    }
}

function Write-EnvironmentInfo {
    Write-Log "Parameters: AppIds=[$($AppIds -join ',')] Force=$Force Reboot=$Reboot NoSync=$NoSync TimeZone=$TimeZone WhatIf=$WhatIfPreference" 'DEBUG'
    Write-Log "PowerShell $($PSVersionTable.PSVersion) ($($PSVersionTable.PSEdition))" 'DEBUG'
    $id = [Security.Principal.WindowsIdentity]::GetCurrent()
    $isAdmin = ([Security.Principal.WindowsPrincipal]$id).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    Write-Log "User: $($id.Name) Elevated: $isAdmin" 'DEBUG'
    $os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue
    if ($os) { Write-Log "OS: $($os.Caption) build $($os.BuildNumber)" 'DEBUG' }
    Write-Log "Computer: $env:COMPUTERNAME windir=$env:windir OutDir=$OutDir" 'DEBUG'
    $svc = Get-Service -Name 'IntuneManagementExtension' -ErrorAction SilentlyContinue
    Write-Log "IME service status: $(if ($svc) { $svc.Status } else { 'not found' })" 'DEBUG'
    $exe = Join-Path $env:ProgramFiles 'Microsoft Intune Management Extension\Microsoft.Management.Services.IntuneWindowsAgent.exe'
    if (Test-Path -LiteralPath $exe) { Write-Log "IME version: $((Get-Item -LiteralPath $exe).VersionInfo.FileVersion)" 'DEBUG' }
    else { Write-Log "IME agent exe not at expected path: $exe" 'DEBUG' }
    Write-Log "Test-Path Win32Apps: $(Test-Path -LiteralPath $ImeBase)" 'DEBUG'
}

function Get-ImeLogLines {
    $files = @(Get-ChildItem -Path $LogDir -Filter '*.log' -File -ErrorAction SilentlyContinue |
        Where-Object { $_.Name -like 'IntuneManagementExtension*' -or $_.Name -like 'AppWorkload*' } |
        Sort-Object LastWriteTime)
    Write-Log "Log directory: $LogDir, matching files: $($files.Count)" 'VERBOSE'
    if ($files.Count -eq 0) { Write-Log "No IME log files found in $LogDir" 'WARN' }
    foreach ($f in $files) {
        $content = @(Get-Content -Path $f.FullName -ErrorAction SilentlyContinue)
        Write-Log "Read $($f.Name): $($content.Count) lines, last write $($f.LastWriteTime)" 'DEBUG'
        $content
    }
}

function Get-ImeAppStatuses {
    param([string[]]$Lines, [string[]]$AppIds)

    $entryPattern = '^<!\[LOG\[(?:Get policies\s*=\s*|\[Win32App\][^{]*?)(?<json>(?:\[\s*)?\{.*\}(?:\s*\])?)\s*\]LOG\]!><time="(?<time>\d{1,2}:\d{2}:\d{2}(?:\.\d{1,7})?)(?:[+-]\d+)?"\s+date="(?<date>\d{1,2}-\d{1,2}-\d{4})"'
    $grsPattern = "GRS value: (?<grs>\d{2}/\d{2}/\d{4} \d{2}:\d{2}:\d{2}) (?:at key|to path:) \S*\\(?<id>$GuidRx)"
    $culture = [Globalization.CultureInfo]::InvariantCulture
    $names = @{}
    $last = @{}
    $outcomes = @{}
    $grs = @{}
    $assigned = @{}
    $reported = @{}
    $invalid = 0
    foreach ($line in $Lines) {
        # GRS holds the UTC time of the app's last install attempt; it is not updated by hourly re-checks.
        if ($line -match $grsPattern) {
            $id = $Matches.id.ToLowerInvariant()
            $attempt = [datetime]::MinValue
            if ([datetime]::TryParseExact($Matches.grs, 'MM/dd/yyyy HH:mm:ss', $culture,
                    [Globalization.DateTimeStyles]::AssumeUniversal -bor [Globalization.DateTimeStyles]::AdjustToUniversal, [ref]$attempt) -and
                $attempt.Year -gt 1 -and (-not $grs.ContainsKey($id) -or $attempt -gt $grs[$id])) {
                $grs[$id] = $attempt
            }
            continue
        }
        if ($line -notmatch '"(?:EnforcementState|ApplicationName|DisplayName|Name)"\s*:' -or
            $line -notmatch $entryPattern) { continue }

        $isPolicy = $line.StartsWith('<![LOG[Get policies')
        $json = $Matches.json
        $timestamp = [datetime]::MinValue
        # IME writes log times in the device's local time without an offset; keep everything in UTC.
        if (-not [datetime]::TryParseExact("$($Matches.date) $($Matches.time)", 'M-d-yyyy H:mm:ss.FFFFFFF',
                $culture, [Globalization.DateTimeStyles]::AssumeLocal -bor [Globalization.DateTimeStyles]::AdjustToUniversal, [ref]$timestamp)) {
            $invalid++
            continue
        }
        try {
            $records = ConvertFrom-Json -InputObject $json -ErrorAction Stop
        } catch [System.ArgumentException], [System.InvalidOperationException] {
            $invalid++
            continue
        }

        foreach ($record in $records) {
            $id = if ($record.ApplicationId) { $record.ApplicationId } elseif ($record.AppId) { $record.AppId } else { $record.Id }
            if ($id -notmatch "^$GuidRx$" -or ($AppIds -and $id -notin $AppIds)) { continue }
            $id = $id.ToLowerInvariant()
            $name = if ($record.ApplicationName) { $record.ApplicationName } elseif ($record.DisplayName) { $record.DisplayName } else { $record.Name }
            if ($name -is [string] -and $name.Trim() -and (-not $names.ContainsKey($id) -or $timestamp -ge $names[$id].Timestamp)) {
                $names[$id] = @{ Name = $name.Trim(); Timestamp = $timestamp }
            }

            # Policy records ("Get policies") carry the assignment intent. Intent 3 is a required install; the
            # assignment time is when IME first received it, and an assignment filter state other than 0 excludes it.
            # Status records also contain Intent, so only policy lines may change the assignment.
            if ($isPolicy) {
                if ($record.Intent -eq 3 -and -not $record.AppApplicabilityStateDueToAssginmentFilters) {
                    if (-not $assigned.ContainsKey($id) -or -not $assigned[$id].Required) {
                        $assigned[$id] = @{ Required = $true; Timestamp = $timestamp }
                    }
                } else {
                    $assigned[$id] = @{ Required = $false; Timestamp = $timestamp }
                }
                continue
            }
            if (-not $reported.ContainsKey($id) -or $timestamp -ge $reported[$id].Timestamp) {
                $reported[$id] = $record | Select-Object @{ n = 'Timestamp'; e = { $timestamp } }, DetectionState, ResultantAppState, EnforcementState
            }

            # DesiredState 2 is install; the same enforcement codes can also describe an uninstall.
            if ($record.DesiredState -ne 2) { continue }
            $status = switch ($record.EnforcementState) {
                1000 { 'INSTALLED' }
                5000 { 'FAILED' }
            }
            if ($status) {
                if (-not $outcomes.ContainsKey($id)) { $outcomes[$id] = [Collections.Generic.List[object]]::new() }
                $outcomes[$id].Add([pscustomobject]@{ Timestamp = $timestamp; Status = $status })
            }
        }
    }
    if ($invalid) { Write-Log "Skipped $invalid IME app record(s) with invalid JSON or timestamps." 'WARN' }

    # IME re-reports installed apps on every check-in (about hourly). Without a GRS value, an installed app is
    # dated by its first success after the latest failure; a failed app by its latest failed report.
    foreach ($id in $outcomes.Keys) {
        $result = $null
        foreach ($outcome in ($outcomes[$id] | Sort-Object Timestamp)) {
            if (-not $result -or $result.Status -ne $outcome.Status -or $outcome.Status -eq 'FAILED') {
                $result = [pscustomobject]@{ AppId = $id; Name = $null; Timestamp = $outcome.Timestamp; Status = $outcome.Status; TimeSource = 'StatusReport' }
            }
        }
        if ($grs.ContainsKey($id)) {
            $result.Timestamp = $grs[$id]
            $result.TimeSource = 'GRS'
        }
        $last[$id] = $result
    }

    # Required apps without an outcome are not yet installed, unless IME detected them (already present) or
    # found them not applicable (enforcement 3000-3999). They are dated by their assignment time.
    foreach ($id in $assigned.Keys) {
        if (-not $assigned[$id].Required -or $last.ContainsKey($id)) { continue }
        $report = $reported[$id]
        if ($report -and ($report.DetectionState -eq 1 -or $report.ResultantAppState -eq 1 -or
                ($report.EnforcementState -ge 3000 -and $report.EnforcementState -lt 4000))) { continue }
        $last[$id] = [pscustomobject]@{ AppId = $id; Name = $null; Timestamp = $assigned[$id].Timestamp; Status = 'PENDING'; TimeSource = 'Assigned' }
    }

    $last.Values | Sort-Object Timestamp, AppId | ForEach-Object {
        if ($names.ContainsKey($_.AppId)) { $_.Name = $names[$_.AppId].Name }
        $_
    }
    foreach ($id in $AppIds) {
        if (-not $last.ContainsKey($id)) {
            $name = if ($names.ContainsKey($id)) { $names[$id].Name }
            [pscustomobject]@{ AppId = $id; Name = $name; Timestamp = $null; Status = 'UNKNOWN' }
        }
    }
}

function Get-RegistryAppNames {
    param([string[]]$AppIds)

    $names = @{}
    $progressPath = Join-Path $ImeBase 'ProvisioningProgress'
    if (Test-Path -LiteralPath $progressPath) {
        $progress = Get-ItemProperty -LiteralPath $progressPath -ErrorAction SilentlyContinue -ErrorVariable progressErrors
        if ($progressErrors) {
            Write-Log "Could not read ESP provisioning progress: $($progressErrors[0].Exception.Message)" 'WARN'
        }
        if ($progress.ProvisioningProgress) {
            try {
                $workloads = (ConvertFrom-Json -InputObject $progress.ProvisioningProgress -ErrorAction Stop).Workloads
                foreach ($workload in $workloads) {
                    if ($workload.WorkloadId -in $AppIds -and $workload.FriendlyName) {
                        $names[$workload.WorkloadId] = $workload.FriendlyName
                    }
                }
            } catch [System.ArgumentException], [System.InvalidOperationException] {
                Write-Log "Could not parse ESP provisioning progress: $($_.Exception.Message)" 'WARN'
            }
        }
    }
    if ($names.Count -lt $AppIds.Count -and (Test-Path -LiteralPath $ImeBase)) {
        foreach ($key in (Get-ChildItem -LiteralPath $ImeBase -Recurse -ErrorAction SilentlyContinue -ErrorVariable nameErrors)) {
            if ($key.PSChildName -notmatch "^(?<id>$GuidRx)(?:_|$)") { continue }
            $id = $Matches.id
            if ($id -notin $AppIds -or $names.ContainsKey($id)) { continue }
            foreach ($valueName in 'DisplayName', 'Name', 'AppName') {
                $name = $key.GetValue($valueName)
                if ($name) { $names[$id] = [string]$name; break }
            }
        }
        if ($nameErrors) { Write-Log "Some IME registry keys could not be read: $($nameErrors[0].Exception.Message)" 'WARN' }
    }
    $names
}

function Write-ImeAppStatuses {
    param([object[]]$Apps)

    $zone = if ($DisplayTimeZone) { $DisplayTimeZone } else { [TimeZoneInfo]::Local }
    foreach ($app in $Apps) {
        $name = if ($app.Name) { $app.Name } else { '(name not found)' }
        if ($app.Timestamp) {
            $label = switch ($app.Status) { 'INSTALLED' { 'Installed' } 'PENDING' { 'Assigned' } default { 'Failed' } }
            $source = switch ($app.TimeSource) { 'StatusReport' { ' (IME status report)' } 'Assigned' { ' (not yet installed)' } default { '' } }
            $shown = [TimeZoneInfo]::ConvertTimeFromUtc($app.Timestamp, $zone)
            $offset = $zone.GetUtcOffset($app.Timestamp)
            $sign = if ($offset -lt [timespan]::Zero) { '-' } else { '+' }
            $time = '{0:yyyy-MM-dd HH:mm:ss} {1}{2:hh\:mm}' -f $shown, $sign, $offset
            Write-Log ('{0} {1}{2} | {3} [{4}]' -f $label, $time, $source, $name, $app.AppId) $app.Status
        } else {
            Write-Log "No installation outcome found for $name [$($app.AppId)]." 'WARN'
        }
    }
}

function Get-GrsHashesForApp {
    param([string]$AppId, [string[]]$Lines)
    $hashes = @{}
    $n = 0
    foreach ($line in $Lines) {
        $n++
        if ($line -notmatch [regex]::Escape($AppId)) { continue }
        if ($line -notmatch 'GRS') { continue }
        foreach ($m in [regex]::Matches($line, $HashRx)) {
            $hashes[$m.Value.ToLower()] = $true
            Write-Log "GRS hash candidate for $AppId at line $n : $($m.Value)" 'DEBUG'
        }
    }
    $hashes.Keys
}

function Remove-AppState {
    param([string]$AppId, [string[]]$GrsHashes)

    if (-not (Test-Path -LiteralPath $ImeBase)) { Write-Log "Win32Apps key not found: $ImeBase" 'WARN'; return 0 }

    $all = @(Get-ChildItem -Path $ImeBase -Recurse -ErrorAction SilentlyContinue)
    Write-Log "Registry: $($all.Count) keys under $ImeBase" 'VERBOSE'
    foreach ($k in $all) { Write-Log " key: $($k.Name)" 'DEBUG' }

    $targets = New-Object System.Collections.Generic.List[object]
    foreach ($k in $all) {
        # App state: <SID or DeviceID>\<AppId> or <AppId>_<something>
        if ($k.PSChildName -eq $AppId -or $k.PSChildName -like "${AppId}_*") {
            Write-Log "Match (app state): $($k.Name)" 'VERBOSE'
            $targets.Add($k)
            continue
        }
        # GRS entry directly under a GRS key
        if ($k.Name -match '\\GRS\\[^\\]+$') {
            $hashHit = $GrsHashes -contains $k.PSChildName.ToLower()
            $valHit  = $false
            foreach ($v in $k.GetValueNames()) {
                $val = [string]$k.GetValue($v)
                Write-Log " GRS value $($k.PSChildName)\$v = $val" 'DEBUG'
                if ($val -like "*$AppId*") { $valHit = $true }
            }
            if ($hashHit -or $valHit) {
                Write-Log "Match (GRS, hash=$hashHit, value=$valHit): $($k.Name)" 'VERBOSE'
                $targets.Add($k)
            }
        }
    }
    Write-Log "Targets for ${AppId}: $($targets.Count)" 'VERBOSE'

    $count = 0
    foreach ($t in $targets) {
        if ($WhatIfPreference) { Write-Log "WHATIF: would delete $($t.Name)" 'INFO'; $count++; continue }
        try {
            if (Test-Path -LiteralPath $t.PSPath) {
                Remove-Item -LiteralPath $t.PSPath -Recurse -Force
                Write-Log "Deleted $($t.Name)" 'INFO'
            } else {
                Write-Log "Already removed (parent deleted first): $($t.Name)" 'DEBUG'
            }
            $count++
        } catch {
            $script:Errors++
            Write-Log "Failed to delete $($t.Name): $($_.Exception.Message)" 'ERROR'
        }
    }
    $count
}

function Invoke-MdmSync {
    # "Schedule #3" under EnterpriseMgmt is the usual MDM sync task. Name may vary by build.
    $tasks = @(Get-ScheduledTask -TaskPath '\Microsoft\Windows\EnterpriseMgmt\*' -ErrorAction SilentlyContinue |
        Where-Object { $_.TaskName -like 'Schedule #3*' })
    Write-Log "MDM sync tasks found: $($tasks.Count)" 'VERBOSE'
    if ($tasks.Count -eq 0) { Write-Log 'No MDM sync task found' 'WARN'; return }
    foreach ($t in $tasks) {
        Write-Log "Task: $($t.TaskPath)$($t.TaskName) state=$($t.State)" 'DEBUG'
        if ($WhatIfPreference) { Write-Log "WHATIF: would start $($t.TaskName)" 'INFO'; continue }
        try {
            Start-ScheduledTask -TaskName $t.TaskName -TaskPath $t.TaskPath
            Write-Log "Started sync task $($t.TaskPath)$($t.TaskName)" 'INFO'
        } catch {
            $script:Errors++
            Write-Log "Sync task failed: $($_.Exception.Message)" 'ERROR'
        }
    }
}

# ===================== MAIN =====================
Write-Host "$ScriptName v$ScriptVersion (Wolfgang Bäck)" -ForegroundColor Cyan
try {
    if ($DebugMode) {
        Start-Transcript -Path $TranscriptFile -Force -WhatIf:$false -Confirm:$false | Out-Null
        Write-Log "Transcript: $TranscriptFile" 'DEBUG'
    }
    Write-Log "=== START $ScriptName v$ScriptVersion ==="
    Write-Log "Times shown in time zone: $($DisplayTimeZone.Id) $(if (-not $TimeZone) { '(device time zone; use -TimeZone to change)' })"
    Write-Log "Output folder: $OutDir" 'VERBOSE'
    Write-EnvironmentInfo
    if ($WhatIfPreference) { Write-Log 'WhatIf mode: no retry, MDM sync or reboot. Diagnostic files will still be written.' 'INFO' }

    # Backup first (read-only for the registry, runs even with -WhatIf)
    if (Test-Path -LiteralPath $ImeBase) {
        Write-Log "Exporting backup: reg.exe export $ImeRegPath -> $BackupFile" 'VERBOSE'
        & reg.exe export $ImeRegPath $BackupFile /y | Out-Null
        Write-Log "reg.exe exit code: $LASTEXITCODE" 'DEBUG'
        if ($LASTEXITCODE -ne 0) { throw "Backup failed (reg.exe exit code $LASTEXITCODE). No retry actions were taken." }
        Write-Log "Backup written: $BackupFile" 'INFO'
    }

    $lines = @(Get-ImeLogLines)
    Write-Log "Total log lines loaded: $($lines.Count)" 'VERBOSE'

    $AppIds = @($AppIds | ForEach-Object { if ($_) { $_.Trim().ToLowerInvariant() } } | Where-Object { $_ } | Select-Object -Unique)
    $apps = @(Get-ImeAppStatuses -Lines $lines -AppIds $AppIds)
    $unnamed = @($apps | Where-Object { -not $_.Name })
    if ($unnamed.Count) {
        $registryNames = Get-RegistryAppNames -AppIds $unnamed.AppId
        foreach ($app in $unnamed) { $app.Name = $registryNames[$app.AppId] }
    }
    if ($apps.Count) {
        Write-Log 'Win32 apps, sorted by install time (not yet installed: assignment time), oldest first:'
        Write-ImeAppStatuses -Apps $apps
    }
    $targets = @(if ($AppIds.Count) { $apps } else { $apps | Where-Object Status -eq 'FAILED' })

    if ($targets.Count -eq 0) {
        Write-Log 'No failed apps found. Pass -AppIds to target apps manually.' 'WARN'
        return
    }

    Write-Log ('Apps selected for retry: ' + (($targets | ForEach-Object {
        $name = if ($_.Name) { $_.Name } else { '(name not found)' }
        "$name [$($_.AppId)]"
    }) -join '; '))

    # Confirmation (skipped with -Force or -WhatIf)
    if (-not $Force -and -not $WhatIfPreference) {
        $answer = Read-Host "Reset these $($targets.Count) app(s) and retry? [y/N]"
        Write-Log "User answer: '$answer'" 'DEBUG'
        if ($answer -notmatch '^(y|yes|j|ja)$') {
            Write-Log 'Cancelled by user. No retry actions were taken.' 'WARN'
            return
        }
    }

    if ($WhatIfPreference) { Write-Log 'WHATIF: would stop IntuneManagementExtension' 'INFO' }
    else {
        Stop-Service -Name 'IntuneManagementExtension' -Force -ErrorAction SilentlyContinue
        Write-Log 'IME stopped' 'INFO'
    }

    foreach ($app in $targets) {
        $id = $app.AppId
        $hashes = @(Get-GrsHashesForApp -AppId $id -Lines $lines)
        Write-Log "App $id : GRS hash(es) found in logs: $(if ($hashes) { $hashes -join ', ' } else { 'none' })" 'INFO'
        $n = Remove-AppState -AppId $id -GrsHashes $hashes
        Write-Log "App $id : $n item(s) processed" 'INFO'
    }

    if ($WhatIfPreference) { Write-Log 'WHATIF: would start IntuneManagementExtension' 'INFO' }
    else {
        Start-Service -Name 'IntuneManagementExtension'
        Write-Log 'IME started' 'INFO'
    }

    if (-not $NoSync) { Invoke-MdmSync }

    if ($Reboot) {
        if ($WhatIfPreference) { Write-Log 'WHATIF: would reboot in 15 seconds' 'INFO' }
        else {
            Write-Log 'Rebooting in 15 seconds' 'INFO'
            shutdown.exe /r /t 15 /c "$ScriptName" | Out-Null
        }
    }

    Write-Log "=== END $ScriptName (errors: $script:Errors) ===" 'INFO'
}
catch {
    Write-Log "FATAL: $($_.Exception.Message)" 'ERROR'
    Write-Log "Position: $($_.InvocationInfo.PositionMessage)" 'ERROR'
    Write-Log "Stack: $($_.ScriptStackTrace)" 'DEBUG'
}
finally {
    if ($DebugMode) { try { Stop-Transcript -WhatIf:$false -Confirm:$false | Out-Null } catch { } }
    Write-Host "$ScriptName finished. Log file: $OutLog" -ForegroundColor Cyan
    if ($DebugMode) { Write-Host "Transcript: $TranscriptFile" }
}