Copiare e incollare questo script di esempio e modificarlo in base alle esigenze dell'ambiente:

<# . SINOSSI     Aggrega i dati JSON di stato di avvio protetto da più dispositivi in report di riepilogo.

. DESCRIZIONE     Legge i file JSON dello stato di avvio protetto raccolti e genera:     - Dashboard HTML con grafici e filtro     - Riepilogo per ConfidenceLevel     - Analisi univoca del contenitore di dispositivi per la strategia      di test     Supporta:     - File per computer: HOSTNAME_latest.json (scelta consigliata)     - File JSON      singolo     Deduplica automaticamente in base a HostName, mantenendo l'ultima versione di CollectionTime.     Per impostazione predefinita, include solo i dispositivi con "Richiesta azione" o "Alta" probabilità     per concentrarsi sui contenitori su cui è possibile eseguire azioni. Usare -IncludeAllConfidenceLevels per eseguire l'override.

. PARAMETER InputPath     Percorso dei file JSON:     - Cartella: legge tutti i file *_latest.json (o *.json se nessun file _latest)     - File: legge un singolo file JSON

. PARAMETER OutputPath     Percorso per i report generati (impostazione predefinita: .\SecureBootReports)

. ESEMPIO     # Aggrega da cartella di file per computer (scelta consigliata)     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$"     # Legge: \\contoso\SecureBootLogs$\*_latest.json

. ESEMPIO     # Percorso di output personalizzato     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -OutputPath "C:\Reports\SecureBoot"

. ESEMPIO     # Includi solo Richiesta azione e Alta probabilità (comportamento predefinito)     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$"     # Esclusi: osservazione, pausa, non supportata

. ESEMPIO     # Includi tutti i livelli di probabilità (ignora filtro)     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncludeAllConfidenceLevels

. ESEMPIO     # Filtro livello di probabilità personalizzato     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncludeConfidenceLevels @("Action Req", "High", "Observation")

. ESEMPIO     # SCALA ENTERPRISE: modalità incrementale : elabora solo i file modificati (esecuzione successiva veloce)     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncrementalMode     # Prima esecuzione: carico completo ~2 ore per dispositivi da 500.000     # Successive esecuzioni: Secondi se non cambia, minuti per delta

. ESEMPIO     # Ignora HTML se non è cambiato nulla (più veloce per il monitoraggio)     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncrementalMode -SkipReportIfUnchanged     # Se nessun file è cambiato dall'ultima esecuzione: circa 5 secondi

. ESEMPIO     # Modalità solo riepilogo: ignora tabelle di dispositivi di grandi dimensioni (da 1 a 2 minuti o più di 20 minuti)     .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -SummaryOnly     # Genera file CSV, ma ignora il dashboard HTML con tabelle di dispositivi complete

. NOTE     Eseguire l'associazione con Detect-SecureBootCertUpdateStatus.ps1 per la distribuzione aziendale.Vedere GPO-DEPLOYMENT-GUIDE.md per la guida completa alla distribuzione.     Il comportamento predefinito esclude i dispositivi di osservazione, in pausa e non supportati     per concentrarsi sui report solo sui bucket di dispositivi su cui è possibile eseguire azioni.#>

param(     [Parametro(Obbligatorio = $true)]     [stringa]$InputPath,          [Parametro(Obbligatorio = $false)]     [string]$OutputPath = ".\SecureBootReports",          [Parametro(Obbligatorio = $false)]     [string]$ScanHistoryPath = ".\SecureBootReports\ScanHistory.json",          [Parametro(Obbligatorio = $false)]     [string]$RolloutStatePath, # Path to RolloutState.json to identify In Progress devices          [Parametro(Obbligatorio = $false)]     [string]$RolloutSummaryPath, # Path to SecureBootRolloutSummary.json from Orchestrator (contains projection data)          [Parametro(Obbligatorio = $false)]     [string[]]$IncludeConfidenceLevels = @("Azione richiesta", "Confidenza elevata"), # Includi solo questi livelli di probabilità (impostazione predefinita: solo bucket utilizzabili)          [Parametro(Obbligatorio = $false)]     [opzione]$IncludeAllConfidenceLevels, # Ignora filtro per includere tutti i livelli      di probabilità     [Parametro(Obbligatorio = $false)]     [opzione]$SkipHistoryTracking,          [Parametro(Obbligatorio = $false)]     [switch]$IncrementalMode, # Enable delta processing - load only changed files since last run          [Parametro(Obbligatorio = $false)]     [stringa]$CachePath, # Percorso della directory cache (impostazione predefinita: OutputPath\.cache)          [Parametro(Obbligatorio = $false)]     [int]$ParallelThreads = 8, # Numero di thread paralleli per il caricamento dei file (PS7+)          [Parametro(Obbligatorio = $false)]     [switch]$ForceFullRefresh, # Forza il ricaricamento completo anche in modalità      incrementale     [Parametro(Obbligatorio = $false)]     [opzione]$SkipReportIfUnchanged, # Ignora la generazione HTML/CSV se non vengono modificati file (solo statistiche di output)          [Parametro(Obbligatorio = $false)]     [switch]$SummaryOnly, # Genera solo statistiche di riepilogo (non tabelle di dispositivi di grandi dimensioni) - molto più velocemente          [Parametro(Obbligatorio = $false)]     [switch]$StreamingMode # Modalità con un utilizzo efficiente della memoria: elabora i chunk, scrivi i file CSV in modo incrementale, mantieni solo i riepiloghi in memoria )

# Elevazione automatica a PowerShell 7 se disponibile (6 volte più veloce per set di dati di grandi dimensioni) if ($PSVersionTable.PSVersion.Major -lt 7) {     $pwshPath = Get-Command pwsh -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source     if ($pwshPath) {         Write-Host "PowerShell $($PSVersionTable.PSVersion) rilevato - riavvio con PowerShell 7 per un'elaborazione più veloce..." -ForegroundColor yellow         # Rebuild argument list from bound parameters         $relaunchArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $MyInvocation.MyCommand.Path)         foreach ($key in $PSBoundParameters.Keys) {             $val = $PSBoundParameters[$key]             if ($val -is [switch]) {                 se ($val. IsPresent) { $relaunchArgs += "-$key" }             } elseif ($val -is [array]) {                 $relaunchArgs += "-$key"                 $relaunchArgs += ($val -join ',')             } else {                 $relaunchArgs += "-$key"                 $relaunchArgs += "$val"             }         }         & $pwshPath @relaunchArgs         uscire $LASTEXITCODE     } }

$ErrorActionPreference = "Continua" $timestamp = Get-Date -Format "yyyyMMdd-HHmmss" $scanTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss" $DownloadUrl = "https://aka.ms/getsecureboot" $DownloadSubPage = "Esempi di distribuzione e monitoraggio"

# Nota: questo script non ha dipendenze da altri script. # Per il set di strumenti completo, scarica da: $DownloadUrl -> $DownloadSubPage

configurazione #region Write-Host "=" * 60 -ForegroundColor Ciano Write-Host "Aggregazione dati di avvio protetto" -ForegroundColor ciano Write-Host "=" * 60 -ForegroundColor Ciano

# Crea directory di output if (-not (Test-Path $OutputPath)) {     New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null }

# Carica dati: supporta i formati CSV (legacy) e JSON (nativo) Write-Host "'nLoad di dati da: $InputPath" -ForegroundColor yellow

# Helper function to normalize device object (handle field name differences) funzione Normalize-DeviceRecord {     param($device)          # Handle Hostname vs HostName (JSON usa Hostname, CSV usa HostName)     se ($device. PSObject.Properties['Hostname'] -and -not $device. PSObject.Properties['HostName']) {         $device | Add-Member -NotePropertyName 'HostName' -NotePropertyValue $device. Hostname -Force     }          # Handle Confidence vs ConfidenceLevel (JSON usa Confidence, CSV usa ConfidenceLevel)     # ConfidenceLevel è il nome del campo ufficiale, a cui viene mappata l'attendibilità     se ($device. PSObject.Properties['Confidence'] -and -not $device. PSObject.Properties['ConfidenceLevel']) {         $device | Add-Member -NotePropertyName 'ConfidenceLevel' -NotePropertyValue $device. Confidence -Force     }          # Tenere traccia dello stato dell'aggiornamento tramite Event1808Count OR UEFICA2023Status="Updated"     # In questo modo è possibile tenere traccia del numero di dispositivi in ogni bucket di confidenza aggiornato     $event 1808 = 0     se ($device. PSObject.Properties['Event1808Count']) {         $event 1808 = [int]$device. Event1808Count     }     $uefiCaUpdated = $false     se ($device. PSObject.Properties['UEFICA2023Status'] -and $device. UEFICA2023Status -eq "Aggiornato") {         $uefiCaUpdated = $true     }          if ($event 1808 -gt 0 -o $uefiCaUpdated) {         # Contrassegnare come aggiornato per la logica di dashboard/implementazione, ma NON ignorare ConfidenceLevel         $device | Add-Member -NotePropertyName 'IsUpdated' -NotePropertyValue $true -Force     } else {         $device | Add-Member -NotePropertyName 'IsUpdated' -NotePropertyValue $false -Force                  # Classificazione ConfidenceLevel:         # - "Alta probabilità", "Sotto osservazione...", "Temporaneamente sospeso...", "Non supportato..." = usare così come è         # - Tutto il resto (null, empty, "UpdateType:...", "Unknown", "N/D") = cade all'azione richiesta nei contatori         # Non è necessaria alcuna normalizzazione: il ramo else del contatore di streaming lo gestisce     }          # Handle OEMManufacturerName vs WMI_Manufacturer (JSON usa OEM*, legacy usa WMI_*)     se ($device. PSObject.Properties['OEMManufacturerName'] -and -not $device. PSObject.Properties['WMI_Manufacturer']) {         $device | Add-Member -NotePropertyName 'WMI_Manufacturer' -NotePropertyValue $device. OEMManufacturerName -Force     }          # Handle OEMModelNumber vs WMI_Model     se ($device. PSObject.Properties['OEMModelNumber'] -and -not $device. PSObject.Properties['WMI_Model']) {         $device | Add-Member -NotePropertyName 'WMI_Model' -NotePropertyValue $device. OEMModelNumber -Force     }          # Handle FirmwareVersion vs BIOSDescription     se ($device. PSObject.Properties['FirmwareVersion'] -and -not $device. PSObject.Properties['BIOSDescription']) {         $device | Add-Member -NotePropertyName 'BIOSDescription' -NotePropertyValue $device. FirmwareVersion -Force     }          restituire $device }

#region Elaborazione incrementale/Gestione cache # Configura percorsi cache if (-$CachePath) {     $CachePath = Join-Path $OutputPath ".cache" } $manifestPath = Join-Path $CachePath "FileManifest.json" $deviceCachePath = Join-Path $CachePath "DeviceCache.json"

# Funzioni di gestione della cache funzione Get-FileManifest {     param([stringa]$Path)     if (Test-Path $Path) {         prova {             $json = Get-Content $Path -Raw | ConvertFrom-Json             # Convert PSObject to hashtable (compatibile CON PS5.1 - PS7 ha -AsHashtable)             $ht = @{}             $json. PSObject.Properties | ForEach-Object { $ht[$_. Name] = $_. Valore }             restituire $ht         } catch {             restituire @{}         }     }     restituire @{} }

funzione Save-FileManifest {     param([tabella hash]$Manifest, [stringa]$Path)     $dir = Split-Path $Path -Parent     if (-not (Test-Path $dir)) {         New-Item -ItemType Directory -Path $dir -Force | Out-Null     }     $Manifest | ConvertTo-Json -Depth 3 -Compress | Set-Content $Path -Force }

funzione Get-DeviceCache {     param([stringa]$Path)     if (Test-Path $Path) {         prova {             $cacheData = Get-Content $Path -Raw | ConvertFrom-Json             Write-Host " Cache dei dispositivi caricata: dispositivi $($cacheData.Count)" -ForegroundColor DarkGray             restituire $cacheData         } catch {             Write-Host "Cache danneggiata, ricrea" -ForegroundColor Yellow             restituire @()         }     }     restituire @() }

funzione Save-DeviceCache {     param($Devices; [stringa]$Path)     $dir = Split-Path $Path -Parent     if (-not (Test-Path $dir)) {         New-Item -ItemType Directory -Path $dir -Force | Out-Null     }     # Converti in matrice e salva     $deviceArray = @($Devices)     $deviceArray | ConvertTo-Json -Depth 10 -Compress | Set-Content $Path -Force     Write-Host " Cache dei dispositivi salvati: dispositivi $($deviceArray.Count)" -ForegroundColor DarkGray }

funzione Get-ChangedFiles {     param(         [System.IO.FileInfo[]]$AllFiles,         [tabella hash]$Manifest     )          $changed = [System.Collections.ArrayList]::new()     $unchanged = [System.Collections.ArrayList]::new()     $newManifest = @{}          # Crea una ricerca senza distinzione tra maiuscole e minuscole dal manifesto (normalizza in minuscolo)     $manifestLookup = @{}     foreach ($mk in $Manifest.Keys) {         $manifestLookup[$mk. ToLowerInvariant()] = $Manifest[$mk]     }          foreach ($file in $AllFiles) {         $key = $file. FullName.ToLowerInvariant() # Normalizzare il percorso in lettere minuscole         $lwt = $file. LastWriteTimeUtc.ToString("o")         $newManifest[$key] = @{             LastWriteTimeUtc = $lwt             Dimensione = $file. Lunghezza         }                  if ($manifestLookup.ContainsKey($key)) {             $cached = $manifestLookup[$key]             se ($cached. LastWriteTimeUtc -eq $lwt -and $cached. Dimensione -eq $file. Lunghezza) {                 [void]$unchanged. Add($file)                 Continuare             }         }         [void]$changed. Aggiungi($file)     }          restituire @{         Modificato = $changed         Unchanged = $unchanged         NewManifest = $newManifest     } }

# Caricamento parallelo ultra-veloce di file utilizzando l'elaborazione in batch funzione Load-FilesParallel {     param(         [System.IO.FileInfo[]]$Files,         [int]$Threads = 8     )

$totalFiles = $Files. Conteggio     # Usa batch di circa 1000 file ciascuno per un migliore controllo della memoria     $batchSize = [matematica]::Min(1000, [matematica]::Soffitto($totalFiles / [matematica]::Max(1, $Threads)))     $batches = [System.Collections.Generic.List[object]]::new()     

for ($i = 0; $i -lt $totalFiles; $i += $batchSize) {         $end = [matematica]::Min($i + $batchSize, $totalFiles)         $batch = $Files[$i.. ($end-1)]         $batches. Aggiungi($batch)     }     Write-Host " ($($batches. Count) batch di ~$batchSize file each)" -NoNewline -ForegroundColor DarkGray     $flatResults = [System.Collections.Generic.List[object]]::new()     # Verificare se è disponibile PowerShell 7+ parallel     $canParallel = $PSVersionTable.PSVersion.Major -ge 7     if ($canParallel -and $Threads -gt 1) {         # PS7+: Processi batch in parallelo         $results = $batches | ForEach-Object -ThrottleLimit $Threads -Parallel {             $batchFiles = $_             $batchResults = [System.Collections.Generic.List[object]]::new()             foreach ($file in $batchFiles) {                 prova {                     $content = [System.IO.File]::ReadAllText($file. FullName) | ConvertFrom-Json                     $batchResults.Add($content)                 } cattura { }             }             $batchResults.ToArray()         }         foreach ($batch in $results) {             if ($batch) { foreach ($item in $batch) { $flatResults.Add($item) } }         }     } else {         # PS5.1 fallback: elaborazione sequenziale (ancora veloce per <file 10K)         foreach ($file in $Files) {             prova {                 $content = [System.IO.File]::ReadAllText($file. FullName) | ConvertFrom-Json                 $flatResults.Add($content)             } cattura { }         }     }     return $flatResults.ToArray() } #endregion                         

$allDevices = @() if (Test-Path $InputPath -PathType Leaf) {     # File JSON singolo     if ($InputPath -like "*.json") {         $jsonContent = Get-Content -Path $InputPath -Raw | ConvertFrom-Json         $allDevices = @($jsonContent) | ForEach-Object { Normalize-DeviceRecord $_ }         Write-Host "Carica record $($allDevices.Count) da file"     } else {         Write-Error "È supportato solo il formato JSON. Il file deve avere un'estensione .json".         uscita 1     } } elseif (Test-Path $InputPath -PathType Container) {     # Folder - Solo JSON     $jsonFiles = @(Get-ChildItem -Path $InputPath -Filter "*.json" -Recurse -ErrorAction SilentlyContinue |                    Where-Object { $_. Name -notmatch "ScanHistory|RolloutState|RolloutPlan" })          # Preferisco *_latest.json file se esistono (modalità per computer)     $latestJson = $jsonFiles | Where-Object { $_. Nome -like "*_latest.json" }     if ($latestJson.Count -gt 0) { $jsonFiles = $latestJson }          $totalFiles = $jsonFiles.Count          if ($totalFiles -eq 0) {         Write-Error "Nessun file JSON trovato in: $InputPath"         uscita 1     }          Write-Host "Trovati $totalFiles file JSON" -ForegroundColor gray          # Helper funzione per abbinare i livelli di probabilità (gestisce sia i moduli brevi che completi)     # Definito in anticipo in modo che sia StreamingMode che i percorsi normali possano usarlo     funzione Test-ConfidenceLevel {         param([string]$Value, [string]$Match)         if ([string]::IsNullOrEmpty($Value)) { restituisce $false }         switch ($Match) {             "HighConfidence" { return $Value -eq "Alta probabilità" }             "UnderObservation" { return $Value -like "Under Observation*" }             "ActionRequired" { return ($Value -like "*Action Required*" -or $Value -eq "Action Required") }             "Temporaneamente sospeso" { restituisce $Value -like "Temporaneamente sospeso*" }             "NotSupported" { return ($Value -like "Not Supported*" -or $Value -eq "Non supportato") }             default { return $false }         }     }          #region MODALITÀ STREAMING - Elaborazione efficiente della memoria per set di dati di grandi dimensioni     # Usa sempre StreamingMode per un'elaborazione efficiente della memoria e un dashboard di nuovo tipo     if (-$StreamingMode) {         Write-Host "Auto-enabling StreamingMode (new-style dashboard)" -ForegroundColor Yellow         $StreamingMode = $true         if (-$IncrementalMode) { $IncrementalMode = $true }     }          # Quando -StreamingMode è abilitato, elabora i file in blocchi mantenendo solo i contatori in memoria.# I dati a livello di dispositivo sono scritti in file JSON per ogni chunk per il caricamento su richiesta nel dashboard.# Utilizzo della memoria: circa 1,5 GB indipendentemente dalle dimensioni del set di dati (contro 10-20 GB senza streaming).if ($StreamingMode) {         Write-Host "MODALITÀ STREAMING abilitata - elaborazione efficiente della memoria" -ForegroundColor green         $streamSw = [System.Diagnostics.Stopwatch]::StartNew()         # CONTROLLO INCREMENTALe: se nessun file è cambiato dall'ultima esecuzione, ignora completamente l'elaborazione         if ($IncrementalMode -and -not $ForceFullRefresh) {             $stManifestDir = Join-Path $OutputPath ".cache"             $stManifestPath = Join-Path $stManifestDir "StreamingManifest.json"             if (Test-Path $stManifestPath) {                 Write-Host "Checking for changes since last streaming run..." -ForegroundColor Cyan                 $stOldManifest = $stManifestPath Get-FileManifest -Path                 if ($stOldManifest.Count -gt 0) {                     $stChanged = $false                     # Controllo rapido: lo stesso numero di file?                     if ($stOldManifest.Count -eq $totalFiles) {                         # Controlla i 100 file PIÙ RECENTI (ordinati per LastWriteTime decrescente)                         # Se un file è stato modificato, avrà il timestamp più recente e verrà visualizzato per primo                         $sampleSize = [matematica]::Min(100, $totalFiles)                         $sampleFiles = $jsonFiles | Sort-Object LastWriteTimeUtc -Descending | Select-Object - Primo $sampleSize                         foreach ($sf in $sampleFiles) {                             $sfKey = $sf. FullName.ToLowerInvariant()                             if (-not $stOldManifest.ContainsKey($sfKey)) {                                 $stChanged = $true                                 Pausa                             }                             # Compare timestamps - cache può essere DateTime o stringa dopo roundtrip JSON                             $cachedLWT = $stOldManifest[$sfKey]. LastWriteTimeUtc                             $fileDT = $sf. LastWriteTimeUtc                             prova {                                 # Se memorizzato nella cache è già DateTime (ConvertFrom-Json auto-converts), utilizzare direttamente                                 if ($cachedLWT -is [DateTime]) {                                     $cachedDT = $cachedLWT.ToUniversalTime()                                 } else {                                     $cachedDT = [DateTimeOffset]::P arse("$cachedLWT"). UtcDateTime                                 }                                 if ([math]::Abs(($cachedDT - $fileDT). TotalSeconds) -gt 1) {                                     $stChanged = $true                                     Pausa                                 }                             } catch {                                 $stChanged = $true                                 Pausa                             }                         }                     } else {                         $stChanged = $true                     }                     if (-$stChanged) {                         # Controlla se esistono file di output                         $stSummaryExists = Get-ChildItem (Percorso join $OutputPath "SecureBoot_Summary_*.csv") -EA SilentlyContinue | Select-Object -Primo 1                         $stDashExists = Get-ChildItem (percorso join $OutputPath "SecureBoot_Dashboard_*.html") -EA SilentlyContinue | Select-Object -Primo 1                         if ($stSummaryExists -and $stDashExists) {                             Write-Host " Nessuna modifica rilevata ($totalFiles file invariati) - elaborazione ignorata" -ForegroundColor green                             Write-Host " Ultimo dashboard: $($stDashExists.FullName)" -ForegroundColor white                             $cachedStats = Get-Content $stSummaryExists.FullName | ConvertFrom-Csv                             Write-Host " Dispositivi: $($cachedStats.TotalDevices) | Aggiornato: $($cachedStats.Updated) | Errori: $($cachedStats.WithErrors)" -ForegroundColor Gray                             Write-Host " Completato in $([math]::Round($streamSw.Elapsed.TotalSeconds, 1))s (nessuna elaborazione necessaria)" -ForegroundColor Green                             $cachedStats reso                         }                     } else {                         # DELTA PATCH: Individuare esattamente quali file sono stati modificati                         Write-Host " Modifiche rilevate - identificazione dei file modificati..." -ForegroundColor yellow                         $changedFiles = [System.Collections.ArrayList]::new()                         $newFiles = [System.Collections.ArrayList]::new()                         foreach ($jf in $jsonFiles) {                             $jfKey = $jf. FullName.ToLowerInvariant()                             if (-not $stOldManifest.ContainsKey($jfKey)) {                                 [void]$newFiles.Add($jf)                             } else {                                 $cachedLWT = $stOldManifest[$jfKey]. LastWriteTimeUtc                                 $fileDT = $jf. LastWriteTimeUtc                                 prova {                                     $cachedDT = if ($cachedLWT -is [DateTime]) { $cachedLWT.ToUniversalTime() } else { [DateTimeOffset]::P arse("$cachedLWT"). UtcDateTime }                                     if ([math]::Abs(($cachedDT - $fileDT). TotalSeconds) -gt 1) { [void]$changedFiles.Add($jf) }                                 } catch { [void]$changedFiles.Add($jf) }                             }                         }                         $totalChanged = $changedFiles.Count + $newFiles.Count                         $changePct = [math]::Round(($totalChanged / $totalFiles) * 100, 1)                         Write-Host " Modificato: $($changedFiles.Count) | Nuovo: $($newFiles.Count) | Totale: $totalChanged ($changePct%)" -ForegroundColor yellow                         if ($totalChanged -gt 0 -and $changePct -lt 10) {                             # DELTA PATCH MODE: <10% modificato, patch dati esistenti                             Write-Host " Delta patch mode ($changePct% < 10%) - patching $totalChanged files..." -ForegroundColor green                             $dataDir = Join-Path $OutputPath "dati"                             # Caricamento dei record del dispositivo modificati/nuovi                             $deltaDevices = @{}                             $allDeltaFiles = @($changedFiles) + @($newFiles)                             foreach ($df in $allDeltaFiles) {                                 prova {                                     $devData = Get-Content $df. FullName -Raw | ConvertFrom-Json                                     $dev = Normalize-DeviceRecord $devData                                     se ($dev. HostName) { $deltaDevices[$dev. HostName] = $dev }                                 } cattura { }                             }                             Write-Host " Caricato $($deltaDevices.Count) modificato record dispositivo" -ForegroundColor Gray                             # Per ogni categoria JSON: rimuovere le voci precedenti per i nomi host modificati, aggiungere nuove voci                             $categoryFiles = @("errori", "known_issues", "missing_kek", "not_updated",                                 "task_disabled", "temp_failures", "perm_failures", "updated_devices",                                 "action_required", "secureboot_off", "rollout_inprogress")                             $changedHostnames = [System.Collections.Generic.HashSet[string]]:new([System.StringComparer]::OrdinalIgnoreCase)                             foreach ($hn in $deltaDevices.Keys) { [void]$changedHostnames.Add($hn) }                             foreach ($cat in $categoryFiles) {                                 $catPath = Join-Path $dataDir "$cat.json"                                 if (Test-Path $catPath) {                                     prova {                                         $catData = Get-Content $catPath -Raw | ConvertFrom-Json                                         # Rimuovere le voci precedenti per i nomi host modificati                                         $catData = @($catData | Where-Object { -not $changedHostnames.Contains($_. HostName) })                                         # Classifica di nuovo ogni dispositivo modificato in categorie                                         # (verrà aggiunto di seguito dopo la classificazione)                                         $catData | ConvertTo-Json -Depth 5 | Set-Content $catPath - Codifica UTF8                                     } cattura { }                                 }                             }                             # Classifica ogni dispositivo modificato e aggiungi i file di categoria corretti                             foreach ($dev in $deltaDevices.Values) {                                 $slim = [ordered]@{                                     HostName = $dev. Hostname                                     WMI_Manufacturer = if ($dev. PSObject.Properties['WMI_Manufacturer']) { $dev. WMI_Manufacturer } else { "" }                                     WMI_Model = if ($dev. PSObject.Properties['WMI_Model']) { $dev. WMI_Model } else { "" }                                     BucketId = if ($dev. PSObject.Properties['BucketId']) { $dev. BucketId } else { "" }                                     ConfidenceLevel = if ($dev. PSObject.Properties['ConfidenceLevel']) { $dev. ConfidenceLevel } else { "" }                                     IsUpdated = $dev. IsUpdated                                     UEFICA2023Error = if ($dev. PSObject.Properties['UEFICA2023Error']) { $dev. UEFICA2023Error } else { $null }                                     SecureBootTaskStatus = if ($dev. PSObject.Properties['SecureBootTaskStatus']) { $dev. SecureBootTaskStatus } else { "" }                                     KnownIssueId = if ($dev. PSObject.Properties['KnownIssueId']) { $dev. KnownIssueId } else { $null }                                     SkipReasonKnownIssue = if ($dev. PSObject.Properties['SkipReasonKnownIssue']) { $dev. SkipReasonKnownIssue } else { $null }                                 }                                 $isUpd = $dev. IsUpdated -eq $true                                 $conf = if ($dev. PSObject.Properties['ConfidenceLevel']) { $dev. ConfidenceLevel } else { "" }                                 $hasErr = (-not [string]::IsNullOrEmpty($dev. UEFICA2023Error) e $dev. UEFICA2023Error -ne "0" -and $dev. UEFICA2023Error -ne "")                                 $tskDis = ($dev. SecureBootTaskEnabled -eq $false -o $dev. SecureBootTaskStatus -eq 'Disabled' -or $dev. SecureBootTaskStatus -eq 'NotFound')                                 $tskNF = ($dev. SecureBootTaskStatus -eq 'NotFound')                                 $sbOn = ($dev. SecureBootEnabled -ne $false -and "$($dev. SecureBootEnabled)" -ne "False")                                 $e 1801 = se ($dev. PSObject.Properties['Event1801Count']) { [int]$dev. Event1801Count } else { 0 }                                 $e 1808 = se ($dev. PSObject.Properties['Event1808Count']) { [int]$dev. Event1808Count } else { 0 }                                 $e 1803 = if ($dev. PSObject.Properties['Event1803Count']) { [int]$dev. Event1803Count } else { 0 }                                 $mKEK = ($e 1803 -gt 0 -o $dev. MissingKEK -eq $true)                                 $hKI = (-not [string]::IsNullOrEmpty($dev. SkipReasonKnownIssue)) -or (-not [string]::IsNullOrEmpty($dev. KnownIssueId)))                                 $rStat = if ($dev. PSObject.Properties['RolloutStatus']) { $dev. RolloutStatus } else { "" }                                 # Aggiungi ai file di categoria corrispondenti                                 $targets = @()                                 if ($isUpd) { $targets += "updated_devices" }                                 if ($hasErr) { $targets += "errors" }                                 if ($hKI) { $targets += "known_issues" }                                 if ($mKEK) { $targets += "missing_kek" }                                 if (-$isUpd -and $sbOn) { $targets += "not_updated" }                                 if ($tskDis) { $targets += "task_disabled" }                                 if (-not $isUpd -and ($tskDis -or (Test-ConfidenceLevel $conf 'TemporarilyPaused'))) { $targets += "temp_failures" }                                 if (-not $isUpd -and ((Test-ConfidenceLevel $conf 'NotSupported') -or ($tskNF -and $hasErr))) { $targets += "perm_failures" }                                 if (-not $isUpd -and (Test-ConfidenceLevel $conf 'ActionRequired')) { $targets += "action_required" }                                 if (-$sbOn) { $targets += "secureboot_off" }                                 if ($e 1801 -gt 0 -and $e 1808 -eq 0 -and -not $hasErr -and $rStat -eq "In Progress") { $targets += "rollout_inprogress" }                                 foreach ($tgt in $targets) {                                     $tgtPath = Join-Path $dataDir "$tgt.json"                                     if (Test-Path $tgtPath) {                                         $existing = Get-Content $tgtPath -Raw | ConvertFrom-Json                                         $existing = @($existing) + @([PSCustomObject]$slim)                                         $existing | ConvertTo-Json -Profondità 5 | Set-Content $tgtPath - Codifica UTF8                                     }                                 }                             }                             # Rigenera i FILE CSV da JSON patchati                             Write-Host " Rigenerazione dei FILE CSV dai dati patchati..." -ForegroundColor Gray                             $newTimestamp = Get-Date -Format "yyyyMMdd-HHmmss"                             foreach ($cat in $categoryFiles) {                                 $catJsonPath = Join-Path $dataDir "$cat.json"                                 $catCsvPath = Join-Path $OutputPath "newTimestamp.csv SecureBoot_${cat}_$"                                 if (Test-Path $catJsonPath) {                                     prova {                                         $catJsonData = Get-Content $catJsonPath -Raw | ConvertFrom-Json                                         if ($catJsonData.Count -gt 0) {                                             $catJsonData | Export-Csv -Path $catCsvPath -NoTypeInformation -Encoding UTF8                                         }                                     } cattura { }                                 }                             }                             # Ricontatte le statistiche dai file JSON patchati                             Write-Host " Riepilogo ricalcolo dai dati patch..." -ForegroundColor Gray                             $patchedStats = [ordered]@{ ReportGeneratedAt = (Get-Date). ToString("yyyy-MM-dd HH:mm:ss") }                             $pTotal = 0; $pUpdated = 0; $pErrors = 0; $pKI = 0; $pKEK = 0                             $pTaskDis = 0; $pTempFail = 0; $pPermFail = 0; $pActionReq = 0; $pSBOff = 0; $pRIP = 0                             foreach ($cat in $categoryFiles) {                                 $catPath = Join-Path $dataDir "$cat.json"                                 $cnt = 0                                 if (Test-Path $catPath) { try { $cnt = (Get-Content $catPath -RAW | ConvertFrom-Json). Conteggio } catch { } }                                 switch ($cat) {                                     "updated_devices" { $pUpdated = $cnt }                                     "errori" { $pErrors = $cnt }                                     "known_issues" { $pKI = $cnt }                                     "missing_kek" { $pKEK = $cnt }                                     "not_updated" { } # calcolato                                     "task_disabled" { $pTaskDis = $cnt }                                     "temp_failures" { $pTempFail = $cnt }                                     "perm_failures" { $pPermFail = $cnt }                                     "action_required" { $pActionReq = $cnt }                                     "secureboot_off" { $pSBOff = $cnt }                                     "rollout_inprogress" { $pRIP = $cnt }                                 }                             }                             $pNotUpdated = (Get-Content (Join-Path $dataDir "not_updated.json") -RAW | ConvertFrom-Json). Conteggio                             $pTotal = $pUpdated + $pNotUpdated + $pSBOff                             Write-Host " Patch Delta completa: $totalChanged dispositivi aggiornati" -ForegroundColor green                             Write-Host " Totale: $pTotal | Aggiornamento: $pUpdated | NotUpdated: $pNotUpdated | Errori: $pErrors" -Primo pianoColore bianco                             # Aggiorna manifesto                             $stManifestDir = Join-Path $OutputPath ".cache"                             $stNewManifest = @{}                             foreach ($jf in $jsonFiles) {                                 $stNewManifest[$jf. FullName.ToLowerInvariant()] = @{                                     LastWriteTimeUtc = $jf. LastWriteTimeUtc.ToString("o"); Dimensione = $jf. Lunghezza                                 }                             }                             Save-FileManifest -Manifest $stNewManifest -Path $stManifestPath                             Write-Host " Completato in $([math]::Round($streamSw.Elapsed.TotalSeconds, 1))s (patch delta - $totalChanged dispositivi)" -ForegroundColor green                             # Fall through to full streaming reprocess to regenerate HTML dashboard                             # I file di dati sono già patchati, quindi questo assicura che il dashboard rimanga aggiornato                             Write-Host " Dashboard rigenerante dai dati patch..." -ForegroundColor Yellow                         } else {                             Write-Host " $changePct% file modificati (>= 10%) - rielaborazione completa in streaming richiesta" -ForegroundColor Yellow                         }                     }                 }             }         }         # Create data subdirectory for on-demand device JSON files         $dataDir = Join-Path $OutputPath "dati"         if (-not (Test-Path $dataDir)) { New-Item -ItemType Directory -Path $dataDir -Force | Out-Null }         # Deduplicazione tramite HashSet (O(1) per ricerca, circa 50 MB per 600.000 nomi host)         $seenHostnames = [System.Collections.Generic.HashSet[string]]:new([System.StringComparer]::OrdinalIgnoreCase)         # Contatori di riepilogo leggeri (sostituisce $allDevices + $uniqueDevices in memoria)         $c = @{             Totale = 0; SBEnabled = 0; SBOff = 0             Aggiornato = 0; HighConf = 0; UnderObs = 0; ActionReq = 0; TempPaused = 0; NotSupported = 0; NoConfData = 0             TaskDisabled = 0; TaskNotFound = 0; TaskDisabledNotUpdated = 0             WithErrors = 0; In Progress = 0; NotYetInitiated = 0; RolloutIn Rollout = 0             WithKnownIssues = 0; WithMissingKEK = 0; TempFailures = 0; PermFailures = 0; NeedsReboot = 0             UpdatePending = 0         }         # Bucket tracking for AtRisk/SafeList (lightweight sets)         $stFailedBuckets = [System.Collections.Generic.HashSet[string]]::new()         $stSuccessBuckets = [System.Collections.Generic.HashSet[string]]::new()         $stAllBuckets = @{}         $stMfrCounts = @{}         $stErrorCodeCounts = @{}; $stErrorCodeSamples = @{}         $stKnownIssueCounts = @{}         # File di dati del dispositivo in modalità batch: accumula per blocco, scarica a chunk boundaries         $stDeviceFiles = @("errori", "known_issues", "missing_kek", "not_updated",             "task_disabled", "temp_failures", "perm_failures", "updated_devices", "action_required",             "secureboot_off", "rollout_inprogress", "under_observation", "needs_reboot", "update_pending")         $stDeviceFilePaths = @{}; $stDeviceFileCounts = @{}         foreach ($dfName in $stDeviceFiles) {             $dfPath = Join-Path $dataDir "$dfName.json"             [System.IO.File]::WriteAllText($dfPath, "['n", [System.Text.Encoding]::UTF8)             $stDeviceFilePaths[$dfName] = $dfPath; $stDeviceFileCounts[$dfName] = 0         }         # Slim device record for JSON output (solo campi essenziali, ~200 byte vs ~2KB completi)         funzione Get-SlimDevice {             param($Dev)             reso [ordinato]@{                 HostName = $Dev.HostName                 WMI_Manufacturer = if ($Dev.PSObject.Properties['WMI_Manufacturer']) { $Dev.WMI_Manufacturer } else { "" }                 WMI_Model = if ($Dev.PSObject.Properties['WMI_Model']) { $Dev.WMI_Model } else { "" }                 BucketId = if ($Dev.PSObject.Properties['BucketId']) { $Dev.BucketId } else { "" }                 ConfidenceLevel = if ($Dev.PSObject.Properties['ConfidenceLevel']) { $Dev.ConfidenceLevel } else { "" }                 IsUpdated = $Dev.IsUpdated                 UEFICA2023Error = if ($Dev.PSObject.Properties['UEFICA2023Error']) { $Dev.UEFICA2023Error } else { $null }                 SecureBootTaskStatus = if ($Dev.PSObject.Properties['SecureBootTaskStatus']) { $Dev.SecureBootTaskStatus } else { "" }                 KnownIssueId = if ($Dev.PSObject.Properties['KnownIssueId']) { $Dev.KnownIssueId } else { $null }                 SkipReasonKnownIssue = if ($Dev.PSObject.Properties['SkipReasonKnownIssue']) { $Dev.SkipReasonKnownIssue } else { $null }                 UEFICA2023Status = if ($Dev.PSObject.Properties['UEFICA2023Status']) { $Dev.UEFICA2023Status } else { $null }                 AvailableUpdatesPolicy = if ($Dev.PSObject.Properties['AvailableUpdatesPolicy']) { $Dev.AvailableUpdatesPolicy } else { $null }                 WinCSKeyApplied = if ($Dev.PSObject.Properties['WinCSKeyApplied']) { $Dev.WinCSKeyApplied } else { $null }             }         }         # Scarica batch su file JSON (modalità di accodamento)         funzione Flush-DeviceBatch {             param([string]$StreamName, [System.Collections.Generic.List[object]]$Batch)             if ($Batch.Count -eq 0) { return }             $fPath = $stDeviceFilePaths[$StreamName]             $fSb = [System.Text.StringBuilder]::new()             foreach ($fDev in $Batch) {                 if ($stDeviceFileCounts[$StreamName] -gt 0) { [void]$fSb.Append(",'n") }                 [void]$fSb.Append(($fDev | ConvertTo-Json -Compress))                 $stDeviceFileCounts[$StreamName]++             }             [System.IO.File]::AppendAllText($fPath, $fSb.ToString(), [System.Text.Encoding]::UTF8)         }         # CICLO DI STREAMING PRINCIPALE         $stChunkSize = if ($totalFiles -le 10000) { $totalFiles } else { 10000 }         $stTotalChunks = [matematica]::Soffitto($totalFiles / $stChunkSize)         $stPeakMemMB = 0         if ($stTotalChunks -gt 1) {             Write-Host "Elaborazione di file $totalFiles in $stTotalChunks blocchi di $stChunkSize (streaming, thread $ParallelThreads):" -ForegroundColor Ciano         } else {             Write-Host "Elaborazione di file $totalFiles (streaming, $ParallelThreads thread):" -ForegroundColor Ciano         }         for ($ci = 0; $ci -lt $stTotalChunks; $ci++) {             $cStart = $ci * $stChunkSize             $cEnd = [matematica]::Min($cStart + $stChunkSize, $totalFiles) - 1             $cFiles = $jsonFiles[$cStart.. $cEnd]             if ($stTotalChunks -gt 1) {                 Write-Host " Chunk $($ci + 1)/$stTotalChunks ($($cFiles.Count) file): " -NoNewline -ForegroundColor Gray             } else {                 Write-Host " Caricamento di file $($cFiles.Count): " -NoNewline -ForegroundColor Gray             }             $cSw = [System.Diagnostics.Stopwatch]::StartNew()             $rawDevices = $ParallelThreads Load-FilesParallel -Files $cFiles -Thread             # Elenchi batch per ogni blocco             $cBatches = @{}             foreach ($df in $stDeviceFiles) { $cBatches[$df] = [System.Collections.Generic.List[object]]::new() }             $cNew = 0; $cDupe = 0             foreach ($raw in $rawDevices) {                 if (-not $raw) { continue }                 $device = Normalize-DeviceRecord $raw                 $hostname = $device. Hostname                 if (-not $hostname) { continue }                 if ($seenHostnames.Contains($hostname)) { $cDupe++; continua }                 [void]$seenHostnames.Add($hostname)                 $cNew++; $c.Totale++                 $sbOn = ($device. SecureBootEnabled -ne $false -and "$($device. SecureBootEnabled)" -ne "False")                 if ($sbOn) { $c.SBEnabled++ } else { $c.SBOff++; $cBatches["secureboot_off"]. Add((Get-SlimDevice $device)) }                 $isUpd = $device. IsUpdated -eq $true                 $conf = if ($device. PSObject.Properties['ConfidenceLevel'] -and $device. ConfidenceLevel) { "$($device. ConfidenceLevel)" } else { "" }                 $hasErr = (-not [string]::IsNullOrEmpty($device. UEFICA2023Error) e "$($device. UEFICA2023Error)" -ne "0" -and "$($device. UEFICA2023Error)" -ne "")                 $tskDis = ($device. SecureBootTaskEnabled -eq $false -or "$($device. SecureBootTaskStatus)" -eq 'Disabled' -or "$($device. SecureBootTaskStatus)" -eq 'NotFound')                 $tskNF = ("$($device. SecureBootTaskStatus)" -eq 'NotFound')                 $bid = if ($device. PSObject.Properties['BucketId'] -and $device. BucketId) { "$($device. BucketId)" } else { "" }                 $e 1808 = if ($device. PSObject.Properties['Event1808Count']) { [int]$device. Event1808Count } else { 0 }                 $e 1801 = if ($device. PSObject.Properties['Event1801Count']) { [int]$device. Event1801Count } else { 0 }                 $e 1803 = se ($device. PSObject.Properties['Event1803Count']) { [int]$device. Event1803Count } else { 0 }                 $mKEK = ($e 1803 -gt 0 -o $device. MissingKEK -eq $true -or "$($device. MissingKEK)" -eq "True")                 $hKI = (-not [string]::IsNullOrEmpty($device. SkipReasonKnownIssue)) -or (-not [string]::IsNullOrEmpty($device. KnownIssueId)))                 $rStat = if ($device. PSObject.Properties['RolloutStatus']) { $device. RolloutStatus } else { "" }                 $mfr = if ($device. PSObject.Properties['WMI_Manufacturer'] -and -not [string]::IsNullOrEmpty($device. WMI_Manufacturer)) { $device. WMI_Manufacturer } else { "Sconosciuto" }                 $bid = if (-not [string]::IsNullOrEmpty($bid)) { $bid } else { "" }                 # Flag aggiornamento pre-calcolo in sospeso (criterio/WinCS applicato, stato non ancora aggiornato, ATTIVATO SB, attività non disabilitata)                 $uefiStatus = if ($device. PSObject.Properties['UEFICA2023Status']) { "$($device. UEFICA2023Status)" } else { "" }                 $hasPolicy = ($device. PSObject.Properties['AvailableUpdatesPolicy'] -and $null -ne $device. AvailableUpdatesPolicy -and "$($device. AvailableUpdatesPolicy)" -ne '')                 $hasWinCS = ($device. PSObject.Properties['WinCSKeyApplied'] -and $device. WinCSKeyApplied -eq $true)                 $statusPending = ([string]::IsNullOrEmpty($uefiStatus) -or $uefiStatus -eq 'NotStarted' -or $uefiStatus -eq 'In Progress')                 $isUpdatePending = (($hasPolicy -o $hasWinCS) -and $statusPending -and -not $isUpd -and $sbOn -and -not $tskDis)                 if ($isUpd) {                     $c.Aggiornato++; [void]$stSuccessBuckets.Add($bid); $cBatches["updated_devices"]. Add((Get-SlimDevice $device))                     # Tenere traccia dei dispositivi aggiornati che richiedono il riavvio (UEFICA2023Status=Updated but Event1808=0)                     if ($e 1808 -eq 0) { $c.NeedsReboot++; $cBatches["needs_reboot"]. Add((Get-SlimDevice $device)) }                 }                 elseif (-non $sbOn) {                     # SecureBoot OFF: fuori ambito, non classificare per confidenza                 }                 else {                     if ($isUpdatePending) { } # Counted separately in Update Pending — mutually exclusive for pie chart                     elseif (Test-ConfidenceLevel $conf "HighConfidence") { $c.HighConf++ }                     elseif (Test-ConfidenceLevel $conf "UnderObservation") { $c.UnderObs++ }                     elseif (Test-ConfidenceLevel $conf "TemporarilyPaused") { $c.TempPaused++ }                     elseif (Test-ConfidenceLevel $conf "NotSupported") { $c.NotSupported++ }                     else { $c.ActionReq++ }                     if ([string]::IsNullOrEmpty($conf)) { $c.NoConfData++ }                 }                 if ($tskDis) { $c.TaskDisabled+++; $cBatches["task_disabled"]. Add((Get-SlimDevice $device)) }                 if ($tskNF) { $c.TaskNotFound++ }                 if (-not $isUpd -and $tskDis) { $c.TaskDisabledNotUpdated++ }                 if ($hasErr) {                     $c.WithErrors++; [void]$stFailedBuckets.Add($bid); $cBatches["errors"]. Add((Get-SlimDevice $device))                     $ec = $device. UEFICA2023Errore                     if (-not $stErrorCodeCounts.ContainsKey($ec)) { $stErrorCodeCounts[$ec] = 0; $stErrorCodeSamples[$ec] = @() }                     $stErrorCodeCounts[$ec]++                     if ($stErrorCodeSamples[$ec]. Conteggio -lt 5) { $stErrorCodeSamples[$ec] += $hostname }                 }                 if ($hKI) {                     $c.WithKnownIssues++; $cBatches["known_issues"]. Add((Get-SlimDevice $device))                     $ki = if (-not [string]::IsNullOrEmpty($device. SkipReasonKnownIssue)) { $device. SkipReasonKnownIssue } else { $device. KnownIssueId }                     if (-not $stKnownIssueCounts.ContainsKey($ki)) { $stKnownIssueCounts[$ki] = 0 }; $stKnownIssueCounts[$ki]++                 }                 if ($mKEK) { $c.WithMissingKEK++; $cBatches["missing_kek"]. Add((Get-SlimDevice $device)) }                 if (-not $isUpd -and ($tskDis -or (Test-ConfidenceLevel $conf 'TemporarilyPaused'))) { $c.TempFailures+++; $cBatches["temp_failures"]. Add((Get-SlimDevice $device)) }                 if (-not $isUpd -and ((Test-ConfidenceLevel $conf 'NotSupported') -or ($tskNF -and $hasErr))) { $c.PermFailures+++; $cBatches["perm_failures"]. Add((Get-SlimDevice $device)) }                 if ($e 1801 -gt 0 -and $e 1808 -eq 0 -and -not $hasErr -and $rStat -eq "InRst") { $c.RolloutIn Alt++; $cBatches["rollout_inprogress"]. Add((Get-SlimDevice $device)) }                 if ($e 1801 -gt 0 -and $e 1808 -eq 0 -and -not $hasErr -and $rStat -ne "In Progress") { $c.NotYetInitiated++ }                 if ($rStat -eq "In Crit" -and $e 1808 -eq 0) { $c.In Crit++ }                 # Aggiornamento in sospeso: criteri o WinCS applicati, stato in sospeso, ATTIVATO SB, attività non disabilitata                 if ($isUpdatePending) {                     $c.UpdatePending++; $cBatches["update_pending"]. Add((Get-SlimDevice $device))                 }                 if (-$isUpd -and $sbOn) { $cBatches["not_updated"]. Add((Get-SlimDevice $device)) }                 # In Dispositivi di osservazione (separati dall'azione richiesta)                 if (-not $isUpd -and (Test-ConfidenceLevel $conf 'UnderObservation')) { $cBatches["under_observation"]. Add((Get-SlimDevice $device)) }                 # Azione richiesta: non aggiornato, SB ATTIVATO, non corrispondente ad altre categorie di confidenza, non aggiornamento in sospeso                 if (-not $isUpd -and $sbOn -and -not $isUpdatePending -and -not (Test-ConfidenceLevel $conf 'HighConfidence') -and -not (Test-ConfidenceLevel $conf 'UnderObservation') -and -not (Test-ConfidenceLevel $conf 'TemporarilyPaused') -and -not (Test-ConfidenceLevel $conf 'NotSupported')) {                     $cBatches["action_required"]. Add((Get-SlimDevice $device))                 }                 if (-not $stMfrCounts.ContainsKey($mfr)) { $stMfrCounts[$mfr] = @{ Total=0; Updated=0; UpdatePending=0; HighConf=0; UnderObs=0; ActionReq=0; TempPaused=0; NotSupported=0; SBOff=0; WithErrors=0 } }                 $stMfrCounts[$mfr]. Totale++                 if ($isUpd) { $stMfrCounts[$mfr]. Aggiornato++ }                 elseif (-not $sbOn) { $stMfrCounts[$mfr]. SBOff++ }                 elseif ($isUpdatePending) { $stMfrCounts[$mfr]. UpdatePending++ }                 elseif (Test-ConfidenceLevel $conf "HighConfidence") { $stMfrCounts[$mfr]. HighConf++ }                 elseif (Test-ConfidenceLevel $conf "UnderObservation") { $stMfrCounts[$mfr]. UnderObs++ }                 elseif (Test-ConfidenceLevel $conf "TemporarilyPaused") { $stMfrCounts[$mfr]. TempPaused++ }                 elseif (Test-ConfidenceLevel $conf "NotSupported") { $stMfrCounts[$mfr]. NotSupported++ }                 else { $stMfrCounts[$mfr]. ActionReq++ }                 if ($hasErr) { $stMfrCounts[$mfr]. WithErrors++ }                 # Tieni traccia di tutti i dispositivi per contenitore (incluso BucketId vuoto)                 $bucketKey = if ($bid -and $bid -ne "") { $bid } else { "(empty)" }                 if (-not $stAllBuckets.ContainsKey($bucketKey)) {                     $stAllBuckets[$bucketKey] = @{ Count=0; Updated=0; Manufacturer=$mfr; Model=""; BIOS="" }                     se ($device. PSObject.Properties['WMI_Model']) { $stAllBuckets[$bucketKey]. Modello = $device. WMI_Model }                     se ($device. PSObject.Properties['BIOSDescription']) { $stAllBuckets[$bucketKey]. BIOS = $device. BIOSDescription }                 }                 $stAllBuckets[$bucketKey]. Conta++                 if ($isUpd) { $stAllBuckets[$bucketKey]. Aggiornato++ }             }             # Scarica batch su disco             foreach ($df in $stDeviceFiles) { Flush-DeviceBatch -StreamName $df -Batch $cBatches[$df] }             $rawDevices = $null; $cBatches = $null; [System.GC]::Collect()             $cSw.Stop()             $cTime = [Math]::Round($cSw.Elapsed.TotalSeconds, 1)             $cRem = $stTotalChunks - $ci - 1             $cEta = if ($cRem -gt 0) { " | ETA: ~$([Math]::Round($cRem * $cSw.Elapsed.TotalSeconds / 60, 1)) min" } else { "" }             $cMem = [math]::Round([System.GC]::GetTotalMemory($false) / 1MB, 0)             if ($cMem -gt $stPeakMemMB) { $stPeakMemMB = $cMem }             Write-Host " +$cNew nuovi, $cDupe duplicati, ${cTime}s | Mem: ${cMem}MB$cEta" -ForegroundColor Green         }         # Finalizzare matrici JSON         foreach ($dfName in $stDeviceFiles) {             [System.IO.File]::AppendAllText($stDeviceFilePaths[$dfName], "'n]", [System.Text.Encoding]::UTF8)             Write-Host " $dfName.json: $($stDeviceFileCounts[$dfName]) devices" -ForegroundColor DarkGray         }         # Compute derived stats         $stAtRisk = 0; $stSafeList = 0         foreach ($bid in $stAllBuckets.Keys) {             $b = $stAllBuckets[$bid]; $nu = $b.Count - $b.Updated             if ($stFailedBuckets.Contains($bid)) { $stAtRisk += $nu }             elseif ($stSuccessBuckets.Contains($bid)) { $stSafeList += $nu }         }         $stAtRisk = [matematica]::Max(0, $stAtRisk - $c.ConErrori)         # NotUptodate = count from not_updated batch (devices with SB ON and not updated)         $stNotUptodate = $stDeviceFileCounts["not_updated"]         $stats = [ordered]@{             ReportGeneratedAt = (Get-Date). ToString("yyyy-MM-dd HH:mm:ss")             TotalDevices = $c.Total; SecureBootEnabled = $c.SBEnabled; SecureBootOFF = $c.SBOff             Updated = $c.Updated; HighConfidence = $c.HighConf; UnderObservation = $c.UnderObs             ActionRequired = $c.ActionReq; TemporarilyPaused = $c.TempPaused; NotSupported = $c.NotSupported             NoConfidenceData = $c.NoConfData; TaskDisabled = $c.TaskDisabled; TaskNotFound = $c.TaskNotFound             TaskDisabledNotUpdated = $c.TaskDisabledNotUpdated             CertificatesUpdated = $c.Updated; NotUptodate = $stNotUptodate; FullyUpdated = $c.Updated             UpdatesPending = $stNotUptodate; UpdatesComplete = $c.Updated             WithErrors = $c.WithErrors; In Progress = $c.In Progress; NotYetInitiated = $c.NotYetInitiated             RolloutInNnett = $c.RolloutIn Rollout; WithKnownIssues = $c.WithKnownIssues             WithMissingKEK = $c.WithMissingKEK; TemporaryFailures = $c.TempFailures; PermanentFailures = $c.PermFailures             NeedsReboot = $c.NeedsReboot; UpdatePending = $c.UpdatePending             AtRiskDevices = $stAtRisk; SafeListDevices = $stSafeList             PercentWithErrors = if ($c.Total -gt 0) { [math]::Round(($c.WithErrors/$c.Total)*100,2) } else { 0 }             PercentAtRisk = if ($c.Total -gt 0) { [math]::Round(($stAtRisk/$c.Total)*100,2) } else { 0 }             PercentSafeList = if ($c.Total -gt 0) { [math]::Round(($stSafeList/$c.Total)*100,2) } else { 0 }             PercentHighConfidence = if ($c.Total -gt 0) { [math]::Round(($c.HighConf/$c.Total)*100,1) } else { 0 }             PercentCertUpdated = if ($c.Total -gt 0) { [math]::Round(($c.Updated/$c.Total)*100,1) } else { 0 }             PercentActionRequired = if ($c.Total -gt 0) { [math]::Round(($c.ActionReq/$c.Total)*100,1) } else { 0 }             PercentNotUptodate = if ($c.Total -gt 0) { [math]::Round($stNotUptodate/$c.Total*100,1) } else { 0 }             PercentFullyUpdated = if ($c.Total -gt 0) { [math]::Round(($c.Updated/$c.Total)*100,1) } else { 0 }             UniqueBuckets = $stAllBuckets.Count; PeakMemoryMB = $stPeakMemMB; ProcessingMode = "Streaming"         }         # Scrittura CSV         [PSCustomObject]$stats | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_Summary_$timestamp.csv") -NoTypeInformation -Encoding UTF8         $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Decrescente | ForEach-Object {             [PSCustomObject]@{ Manufacturer=$_. Chiave; Count=$_. Value.Total; Updated=$_. Value.Updated; HighConfidence=$_. Value.HighConf; ActionRequired=$_. Value.ActionReq }         } | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_ByManufacturer_$timestamp.csv") -NoTypeInformation -Encoding UTF8         $stErrorCodeCounts.GetEnumerator() | valore Sort-Object -Decrescente | ForEach-Object {             [PSCustomObject]@{ ErrorCode=$_. Chiave; Count=$_. Valore; SampleDevices=($stErrorCodeSamples[$_. Chiave] -join ", ") }         } | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_ErrorCodes_$timestamp.csv") -NoTypeInformation -Encoding UTF8         $stAllBuckets.GetEnumerator() | Sort-Object { $_. Value.Count } -Descending | ForEach-Object {             [PSCustomObject]@{ BucketId=$_. Chiave; Count=$_. Value.Count; Updated=$_. Value.Updated; NotUpdated=$_. Valore.Conteggio-$_. Value.Updated; Manufacturer=$_. Value.Manufacturer }         } | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_UniqueBuckets_$timestamp.csv") -NoTypeInformation -Encoding UTF8         # Genera CSV compatibili con orchestrazione (nomi file previsti per Start-SecureBootRolloutOrchestrator.ps1)         $notUpdatedJsonPath = Join-Path $dataDir "not_updated.json"         if (Test-Path $notUpdatedJsonPath) {             prova {                 $nuData = Get-Content $notUpdatedJsonPath -Raw | ConvertFrom-Json                 if ($nuData.Count -gt 0) {                     # Csv notUptodate - cerca *NotUptodate*.csv                     $nuData | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_NotUptodate_$timestamp.csv") -NoTypeInformation -Encoding UTF8                     Write-Host " CSV dell'agente di orchestrazione: SecureBoot_NotUptodate_$timestamp.csv (dispositivi $($nuData.Count)" -ForegroundColor Gray                 }             } cattura { }         }         # Scrittura di dati JSON per il dashboard         $stats | ConvertTo-Json -Profondità 3 | Set-Content (Join-Path $dataDir "summary.json") - Codifica UTF8         # TRACCIAMENTO STORICO: salvare il punto dati per il grafico di tendenza         # Usare una posizione cache stabile in modo che i dati di tendenza persistono nelle cartelle di aggregazione con timestamp.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   # Se OutputPath ha l'aspetto di "...\Aggregation_yyyyMMdd_HHmmss", la cache viene inserita nella cartella padre.# In caso contrario, la cache viene memorizzata all'interno di OutputPath stesso.$parentDir = Split-Path $OutputPath -Parent         $leafName = Split-Path $OutputPath -Leaf         if ($leafName -match '^Aggregation_\d{8}' -or $leafName -eq 'Aggregation_Current') {             # Cartella con timestamp creata dall'agente di orchestrazione: usare l'elemento padre per la cache stabile             $historyPath = Join-Path $parentDir ".cache\trend_history.json"         } else {             $historyPath = Join-Path $OutputPath ".cache\trend_history.json"         }         $historyDir = Split-Path $historyPath -Parent         if (-not (Test-Path $historyDir)) { New-Item -ItemType Directory -Path $historyDir -Force | Out-Null }         $historyData = @()         if (test-path $historyPath) {             prova { $historyData = @(Get-Content $historyPath -RAW | ConvertFrom-Json) } catch { $historyData = @() }         }         # Controlla anche all'interno di OutputPath\.cache\ (percorso legacy delle versioni precedenti)         # Unisci gli eventuali punti dati non già presenti nella cronologia principale         if ($leafName -eq 'Aggregation_Current' -o $leafName -match '^Aggregation_\d{8}') {             $innerHistoryPath = Join-Path $OutputPath ".cache\trend_history.json"             if ((Test-Path $innerHistoryPath) -and $innerHistoryPath -ne $historyPath) {                 prova {                     $innerData = @(Get-Content $innerHistoryPath -RAW | ConvertFrom-Json)                     $existingDates = @($historyData | ForEach-Object { $_. Data })                     foreach ($entry in $innerData) {                         se ($entry. Data e $entry. Date -notin $existingDates) {                             $historyData += $entry                         }                     }                     if ($innerData.Count -gt 0) {                         Write-Host " Dati $($innerData.Count) uniti dalla cache interna" -ForegroundColor DarkGray                     }                 } cattura { }             }         }

# BOOTSTRAP: Se la cronologia delle tendenze è vuota/sparse, ricostruire dai dati storici         if ($historyData.Count -lt 2 -and ($leafName -match '^Aggregation_\d{8}' -or $leafName -eq 'Aggregation_Current')) {             Write-Host " Bootstrapping trend history from historical data..." -ForegroundColor Yellow             $dailyData = @{}                          # Source 1: Summary CSVs inside current folder (Aggregation_Current keeps all Summary CSVs)             $localSummaries = Get-ChildItem $OutputPath -Filter "SecureBoot_Summary_*.csv" -EA SilentlyContinue | nome Sort-Object             foreach ($summCsv in $localSummaries) {                 prova {                     $summ = Import-Csv $summCsv.FullName | Select-Object -Primo 1                     se ($summ. TotalDevices -and [int]$summ. TotalDevices -gt 0 -e $summ. ReportGeneratedAt) {                         $dateStr = ([datetime]$summ. ReportGeneratedAt). ToString("aaaa-MM-gg")                         $updated = if ($summ. Aggiornato) { [int]$summ. Aggiornato } else { 0 }                         $notUpd = if ($summ. NotUptodate) { [int]$summ. NotUptodate } else { [int]$summ. TotalDevices - $updated }                         $dailyData[$dateStr] = [PSCustomObject]@{                             Date = $dateStr; Total = [int]$summ. TotalDevices; Updated = $updated; NotUpdated = $notUpd                             NeedsReboot = 0; Errori = 0; ActionRequired = if ($summ. ActionRequired) { [int]$summ. ActionRequired } else { 0 }                         }                     }                 } cattura { }             }                          # Origine 2: vecchie cartelle Aggregation_* con timestamp (legacy, se esistono ancora)             $aggFolders = Get-ChildItem $parentDir -Directory -Filter "Aggregation_*" -EA SilentlyContinue |                 Where-Object { $_. Name -match '^Aggregation_\d{8}' } |                 nome Sort-Object             foreach ($folder in $aggFolders) {                 $summCsv = Get-ChildItem $folder. FullName -Filter "SecureBoot_Summary_*.csv" -EA SilentlyContinue | Select-Object -Primo 1                 if ($summCsv) {                     prova {                         $summ = Import-Csv $summCsv.FullName | Select-Object -First 1                         se ($summ. TotalDevices -and [int]$summ. TotalDevices -gt 0) {                             $dateStr = $folder. Name -replace '^Aggregation_(\d{4})(\d{2})(\d{2})_.*', '$1-$2-$3'                             $updated = if ($summ. Aggiornato) { [int]$summ. Aggiornato } else { 0 }                             $notUpd = if ($summ. NotUptodate) { [int]$summ. NotUptodate } else { [int]$summ. TotalDevices - $updated }                             $dailyData[$dateStr] = [PSCustomObject]@{                                 Date = $dateStr; Total = [int]$summ. TotalDevices; Updated = $updated; NotUpdated = $notUpd                                 NeedsReboot = 0; Errori = 0; ActionRequired = if ($summ. ActionRequired) { [int]$summ. ActionRequired } else { 0 }                             }                         }                     } cattura { }                 }             }                          # Fonte 3: RolloutState.json WaveHistory (ha timestamp per onda del giorno 1)             # Fornisce punti dati di base anche quando non esistono cartelle di aggregazione precedenti             $rolloutStatePaths = @(                 (Join-Path $parentDir "RolloutState\RolloutState.json"),                 (Join-Path $OutputPath "RolloutState\RolloutState.json")             )             foreach ($rsPath in $rolloutStatePaths) {                 if (Test-Path $rsPath) {                     prova {                         $rsData = Get-Content $rsPath -Raw | ConvertFrom-Json                         if ($rsData.WaveHistory) {                             # Utilizzare le date di inizio onda come punti dati di tendenza                             # Calcola i dispositivi cumulativi mirati a ogni onda                             $cumulativeTargeted = 0                             foreach ($wave in $rsData.WaveHistory) {                                 se ($wave. StartedAt -and $wave. DeviceCount) {                                     $waveDate = ([datetime]$wave. StartedAt). ToString("aaaa-MM-gg")                                     $cumulativeTargeted += [int]$wave. DeviceCount                                     if (-not $dailyData.ContainsKey($waveDate)) {                                         # Approssimativo: all'ora di inizio delle onde, sono stati aggiornati solo i dispositivi delle onde precedenti                                         $dailyData[$waveDate] = [PSCustomObject]@{                                             Date = $waveDate; Totale = $c.Totale; Updated = [math]::Max(0, $cumulativeTargeted - [int]$wave. DeviceCount)                                             NotUpdated = $c.Total - [math]::Max(0, $cumulativeTargeted - [int]$wave. DeviceCount)                                             NeedsReboot = 0; Errori = 0; ActionRequired = 0                                         }                                     }                                 }                             }                         }                     } cattura { }                     break # Use first found                 }             }

if ($dailyData.Count -gt 0) {                 $historyData = @($dailyData.GetEnumerator() | chiave di Sort-Object | ForEach-Object { $_. Valore })                 Write-Host " Bootstrapped $($historyData.Count) data points from historical summaries" -ForegroundColor Green             }         }

# Aggiungere il punto dati corrente (deduplicazione per giorno- mantieni l'ultimo al giorno)         $todayKey = (Get-Date). ToString("aaaa-MM-gg")         $existingToday = $historyData | Where-Object { "$($_. Date)" -like "$todayKey*" }         if ($existingToday) {             # Sostituisci la voce corrente             $historyData = @($historyData | Where-Object { "$($_. Date)" -notlike "$todayKey*" })         }         $historyData += [PSCustomObject]@{             Date = $todayKey             Totale = $c.Totale             Updated = $c.Updated             NotUpdated = $stNotUptodate             NeedsReboot = $c.NeedsReboot             Errors = $c.WithErrors             ActionRequired = $c.ActionReq         }         # Rimuovi punti dati non validi (0 in totale) e mantieni gli ultimi 90         $historyData = @($historyData | Where-Object { [int]$_. Totale -gt 0 })         # Nessun limite — i dati di tendenza sono circa 100 byte/entrata, un anno completo = ~36 KB         $historyData | ConvertTo-Json -Profondità 3 | Set-Content $historyPath -Codifica UTF8         Write-Host " Cronologia tendenza: $($historyData.Count) punti dati" -ForegroundColor DarkGray                  # Creare dati del grafico di tendenza per HTML         $trendLabels = ($historyData | ForEach-Object { "'$($_. Date)'" }) -join ","         $trendUpdated = ($historyData | ForEach-Object { $_. Aggiornato }) -join ","         $trendNotUpdated = ($historyData | ForEach-Object { $_. NotUpdated }) -join ","         $trendTotal = ($historyData | ForEach-Object { $_. Total }) -join ","         # Proiezione: estendere la linea di tendenza utilizzando il raddoppiamento esponenziale (2,4,8,16...)         # Deriva la dimensione dell'onda e il periodo di osservazione dai dati della cronologia delle tendenze effettive.# - Dimensione onda = il più grande aumento di un singolo periodo registrato nella storia (l'onda più recente distribuita)         # - Giorni di osservazione = giorni medi di calendario tra i punti dati di tendenza (frequenza di esecuzione)         # Quindi raddoppia le dimensioni dell'onda ogni periodo, abbinando la strategia di crescita 2x dell'orchestratore.$projLabels = ""; $projUpdated = ""; $projNotUpdated = ""; $hasProjection = $false         if ($historyData.Count -ge 2) {             $lastUpdated = $c.Aggiornato             $remaining = $stNotUptodate # Solo dispositivi SB-ON non aggiornati (escluso SecureBoot OFF)             $projDates = @(); $projValues = @(); $projNotUpdValues = @()             $projDate = Get-Date

# Derivare le dimensioni delle onde e il periodo di osservazione dalla cronologia delle tendenze             $increments = @()             $dayGaps = @()             for ($hi = 1; $hi -lt $historyData.Count; $hi++) {                 $inc = $historyData[$hi]. Aggiornato - $historyData[$hi-1]. Aggiornato                 if ($inc -gt 0) { $increments += $inc }                 prova {                     $d 1 = [datetime]::P arse($historyData[$hi-1]. Data)                     $d 2 = [datetime]::P arse($historyData[$hi]. Data)                     $gap = ($d 2 - $d 1). TotalDays                     if ($gap -gt 0) { $dayGaps += $gap }                 } cattura {}             }             # Dimensione onda = incremento positivo più recente (onda corrente), fallback alla media, minimo 2             $waveSize = if ($increments. Count -gt 0) {                 [matematica]::Max(2, $increments[-1])             } altro { 2 }             # Periodo di osservazione = distanza media tra i punti dati (giorni del calendario per onda), minimo 1             $waveDays = if ($dayGaps.Count -gt 0) {                 [math]::Max(1, [math]::Round(($dayGaps | Measure-Object -Average). Media, 0))             } altro { 1 }

            Write-Host " Proiezione: waveSize=$waveSize (dall'ultimo incremento), waveDays=$waveDays (avg gap from history)" -ForegroundColor DarkGray

$dayCounter = 0             # Proietta fino a quando tutti i dispositivi non vengono aggiornati o fino a 365 giorni al massimo             for ($pi = 1; $pi -le 365; $pi++) {                 $projDate = $projDate.AddDays(1)                 $dayCounter++                 # A ogni confine del periodo di osservazione, distribuisci un'onda poi raddoppia                 if ($dayCounter -ge $waveDays) {                     $devicesThisWave = [matematica]::Min($waveSize, $remaining)                     $devicesThisWave $lastUpdated +=                     $devicesThisWave $remaining -=                     if ($lastUpdated -gt ($c.Aggiornato + $stNotUptodate)) { $lastUpdated = $c.Aggiornato + $stNotUptodate; $remaining = 0 }                     # Dimensioni della doppia onda per il periodo successivo (strategia 2x dell'orchestrazione)                     $waveSize = $waveSize * 2                     $dayCounter = 0                 }                 $projDates += "'$($projDate.ToString("yyyy-MM-dd"))'"                 $projValues += $lastUpdated                 $projNotUpdValues += [matematica]::Max(0, $remaining)                 if ($remaining -le 0) { break }             }             $projLabels = $projDates -join ","             $projUpdated = $projValues -join ","             $projNotUpdated = $projNotUpdValues -join ","             $hasProjection = $projDates.Count -gt 0         } elseif ($historyData.Count -eq 1) {             Write-Host " Proiezione: è necessario almeno 2 punti dati di tendenza per derivare l'intervallo tra le onde" -ForegroundColor DarkGray         }         # Creare stringhe di dati del grafico combinate per la stringa qui         $allChartLabels = if ($hasProjection) { "$trendLabels,$projLabels" } else { $trendLabels }         $projDataJS = if ($hasProjection) { $projUpdated } else { "" }         $projNotUpdJS = if ($hasProjection) { $projNotUpdated } else { "" }         $histCount = ($historyData | Misura-Oggetto). Conteggio         $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Decrescente | ForEach-Object {             @{ name=$_. Chiave; total=$_. Value.Total; updated=$_. Value.Updated; highConf=$_. Value.HighConf; actionReq=$_. Value.ActionReq }         } | ConvertTo-Json -Profondità 3 | Set-Content (Join-Path $dataDir "manufacturers.json") - Codifica UTF8         # Converti i file di dati JSON in CSV per i download di Excel leggibili dall'uomo         Write-Host "Conversione dei dati del dispositivo in CSV per il download di Excel..." -ForegroundColor Gray         foreach ($dfName in $stDeviceFiles) {             $jsonFile = Join-Path $dataDir "$dfName.json"             $csvFile = Join-Path $OutputPath "timestamp.csv SecureBoot_${dfName}_$"             if (Test-Path $jsonFile) {                 prova {                     $jsonData = Get-Content $jsonFile -Raw | ConvertFrom-Json                     if ($jsonData.Count -gt 0) {                         # Include colonne aggiuntive per update_pending CSV                         $selectProps = if ($dfName -eq "update_pending") {                             @('HostName', 'WMI_Manufacturer', 'WMI_Model', 'BucketId', 'ConfidenceLevel', 'IsUpdated', 'UEFICA2023Status', 'UEFICA2023Error', 'AvailableUpdatesPolicy', 'WinCSKeyApplied', 'SecureBootTaskStatus')                         } else {                             @('HostName', 'WMI_Manufacturer', 'WMI_Model', 'BucketId', 'ConfidenceLevel', 'IsUpdated', 'UEFICA2023Error', 'SecureBootTaskStatus', 'KnownIssueId', 'SkipReasonKnownIssue')                         }                         $jsonData | Select-Object $selectProps |                             Export-Csv -Path $csvFile -NoTypeInformation -Encoding UTF8                         Write-Host " $dfName -> $($jsonData.Count) righe -> CSV" -ForegroundColor DarkGray                     }                 } cattura { Write-Host " $dfName - ignorato" -ForegroundColor DarkYellow }             }         }         # Genera dashboard HTML autonomo         $htmlPath = Join-Path $OutputPath "timestamp.html SecureBoot_Dashboard_$"         Write-Host "Generazione di dashboard HTML autonomo..." -ForegroundColor Yellow         # PROIEZIONE VELOCITÀ: calcola dalla cronologia di scansione o dal riepilogo precedente         $stDeadline = [datetime]"2026-06-24" # KEK certexpiry         $stDaysToDeadline = [matematica]::Max(0, ($stDeadline - (Ottieni-Data)). Giorni)         $stDevicesPerDay = 0         $stProjectedDate = $null         $stVelocitySource = "N/D"         $stWorkingDays = 0         $stCalendarDays = 0         # Prova prima la cronologia delle tendenze (leggera, già mantenuta dall'aggregatore e sostituisce ScanHistory.json)         if ($historyData.Count -ge 2) {             $validHistory = @($historyData | Where-Object { [int]$_. Totale -gt 0 -e [int]$_. Aggiornato -ge 0 })             if ($validHistory.Count -ge 2) {                 $prev = $validHistory[-2]; $curr = $validHistory[-1]                 $prevDate = [datetime]::P arse($prev. Date.Substring(0, [Math]::Min(10, $prev. Date.Length)))                 $currDate = [datetime]::P arse($curr. Date.Substring(0, [Math]::Min(10, $curr. Date.Length)))                 $daysDiff = ($currDate - $prevDate). TotalDays                 if ($daysDiff -gt 0) {                     $updDiff = [int]$curr. Aggiornato - [int]$prev. Aggiornato                     if ($updDiff -gt 0) {                         $stDevicesPerDay = [math]::Round($updDiff / $daysDiff, 0)                         $stVelocitySource = "TrendHistory"                     }                 }             }         }         # Prova il riepilogo dell'implementazione dell'agente di orchestrazione (con velocità pre-calcolata)         if ($stVelocitySource -eq "N/D" -and $RolloutSummaryPath -and (Test-Path $RolloutSummaryPath)) {             prova {                 $rolloutSummary = Get-Content $RolloutSummaryPath -Raw | ConvertFrom-Json                 if ($rolloutSummary.DevicesPerDay -and [double]$rolloutSummary.DevicesPerDay -gt 0) {                     $stDevicesPerDay = [math]::Round([double]$rolloutSummary.DevicesPerDay, 1)                     $stVelocitySource = "Orchestratore"                     if ($rolloutSummary.ProjectedCompletionDate) {                         $stProjectedDate = $rolloutSummary.ProjectedCompletionDate                     }                     if ($rolloutSummary.WorkingDaysRemaining) { $stWorkingDays = [int]$rolloutSummary.WorkingDaysRemaining }                     if ($rolloutSummary.CalendarDaysRemaining) { $stCalendarDays = [int]$rolloutSummary.CalendarDaysRemaining }                 }             } cattura { }         }         # Fallback: prova il csv di riepilogo precedente (cerca nella cartella corrente E nelle cartelle di aggregazione padre/pari)         if ($stVelocitySource -eq "N/D") {             $searchPaths = @(                 (Join-Path $OutputPath "SecureBoot_Summary_*.csv")             )             # Cerca anche cartelle di aggregazione di pari livello (l'agente di orchestrazione crea una nuova cartella a ogni esecuzione)             $parentPath = Split-Path $OutputPath -Parent             if ($parentPath) {                 $searchPaths += (Percorso join $parentPath "Aggregation_*\SecureBoot_Summary_*.csv")                 $searchPaths += (percorso di join $parentPath "SecureBoot_Summary_*.csv")             }             $prevSummary = $searchPaths | ForEach-Object { Get-ChildItem $_ -EA SilentlyContinue } | Sort-Object LastWriteTime -Descending | Select-Object -First 1             if ($prevSummary) {                 prova {                     $prevStats = Get-Content $prevSummary.FullName | ConvertFrom-Csv                     $prevDate = [datetime]$prevStats.ReportGeneratedAt                     $daysSinceLast = ((Get-Date) - $prevDate). TotalDays                     if ($daysSinceLast -gt 0,01) {                         $prevUpdated = [int]$prevStats.Updated                         $updDelta = $c.Aggiornato - $prevUpdated                         if ($updDelta -gt 0) {                             $stDevicesPerDay = [math]::Round($updDelta / $daysSinceLast, 0)                             $stVelocitySource = "PreviousReport"                         }                     }                 } cattura { }             }         }         # Fallback: calcola la velocità dalla durata completa della cronologia delle tendenze (primo vs ultimo punto dati)         if ($stVelocitySource -eq "N/D" -and $historyData.Count -ge 2) {             $validHistory = @($historyData | Where-Object { [int]$_. Totale -gt 0 -e [int]$_. Aggiornato -ge 0 })             if ($validHistory.Count -ge 2) {                 $first = $validHistory[0]                 $last = $validHistory[-1]                 $firstDate = [datetime]::P arse($first. Date.Substring(0, [Math]::Min(10, $first. Date.Length)))                 $lastDate = [datetime]::P arse($last. Date.Substring(0, [Math]::Min(10, $last. Date.Length)))                 $daysDiff = ($lastDate - $firstDate). TotalDays                 if ($daysDiff -gt 0) {                     $updDiff = [int]$last. Aggiornato - [int]$first. Aggiornato                     if ($updDiff -gt 0) {                         $stDevicesPerDay = [math]::Round($updDiff / $daysDiff, 1)                         $stVelocitySource = "TrendHistory"                     }                 }             }         }         # Calcolare la proiezione utilizzando il raddoppiamento esponenziale (coerente con il grafico di tendenza)         # Riutilizzare i dati di proiezione già calcolati per il grafico, se disponibili         if ($hasProjection -and $projDates.Count -gt 0) {             # Usa l'ultima data prevista (quando tutti i dispositivi vengono aggiornati)             $lastProjDateStr = $projDates[-1] -replace "'", ""             $stProjectedDate = ([datetime]::P arse($lastProjDateStr)). ToString("MMM dd, yyyy")             $stCalendarDays = ([datetime]::P arse($lastProjDateStr) - (Get-Date)). Giorni             $stWorkingDays = 0             $d = Get-Date             for ($i = 0; $i -lt $stCalendarDays; $i++) {                 $d = $d.AddDays(1)                 if ($d.DayOfWeek -ne 'Saturday' -and $d.DayOfWeek -ne 'Sunday') { $stWorkingDays++ }             }         } elseif ($stDevicesPerDay -gt 0 -e $stNotUptodate -gt 0) {             # Fallback: proiezione lineare se non sono disponibili dati esponenziali             $daysNeeded = [matematica]::Soffitto($stNotUptodate / $stDevicesPerDay)             $stProjectedDate = (Get-Date). AddDays($daysNeeded). ToString("MMM dd, yyyy")             $stWorkingDays = 0; $stCalendarDays = $daysNeeded             $d = Get-Date             for ($i = 0; $i -lt $daysNeeded; $i++) {                 $d = $d.AddDays(1)                 if ($d.DayOfWeek -ne 'Saturday' -and $d.DayOfWeek -ne 'Sunday') { $stWorkingDays++ }             }         }         # Velocità di compilazione HTML         $velocityHtml = if ($stDevicesPerDay -gt 0) {             "<div><forte>&#128640; Devices/Day:</strong> $($stDevicesPerDay.ToString('N0')) (source: $stVelocitySource)</div>" +             "<div><forte>&#128197; Completamento previsto:</strong> $stProjectedDate" +             $(if ($stProjectedDate -and [datetime]::P arse($stProjectedDate) -gt $stDeadline) { " <span style='color:#dc3545; font-weight:bold'>&#9888; PAST DEADLINE</span>" } else { " <span style='color:#28a745'>&#10003; Before deadline</span>" }) +             "</div>" +             "<div><forte>&#128336; Giorni lavorativi:</strong> $stWorkingDays | <giorni di>Calendar forti:</strong> $stCalendarDays</div>" +             "<div style='font-size:.8em; colore:#888'>Scadenza: 24 giugno 2026 (scadenza certificato KEK) | Giorni rimanenti: $stDaysToDeadline</div>"         } else {             "<div style='padding:8px; sfondo:#fff3cd; border-radius:4px; bordo-sinistra:3px #ffc107'>" +             "<forte>&#128197; Completamento previsto:</strong> dati insufficienti per il calcolo della velocità.                                                                                  " +             "Esegui l'aggregazione almeno due volte con modifiche dei dati per stabilire una tariffa.<br/>" +             "<forte>Scadenza:</strong> 24 giugno 2026 (scadenza certificato KEK) | <giorni di>rimanenti:</strong> $stDaysToDeadline</div>"         }                  # Conto alla rovescia per la scadenza del certificato         $certToday = Get-Date         $certKekExpiry = [datetime]"2026-06-24"         $certUefiExpiry = [datetime]"2026-06-27"         $certPcaExpiry = [datetime]"2026-10-19"         $daysToKek = [matematica]::Max(0; ($certKekExpiry - $certToday). Giorni)         $daysToUefi = [matematica]::Max(0, ($certUefiExpiry - $certToday). Giorni)         $daysToPca = [matematica]::Max(0, ($certPcaExpiry - $certToday). Giorni)         $certUrgency = if ($daysToKek -lt 30) { '#dc3545' } elseif ($daysToKek -lt 90) { '#fd7e14' } else { '#28a745' }                  # Helper: leggi i record da JSON, riepilogo del bucket di compilazione + prime N righe dispositivo         $maxInlineRows = 200         funzione Build-InlineTable {             param([string]$JsonPath, [int]$MaxRows = 200, [string]$CsvFileName = "")             $bucketSummary = ""             $deviceRows = ""             $totalCount = 0             if (Test-Path $JsonPath) {                 prova {                     $data = Get-Content $JsonPath -Raw | ConvertFrom-Json                     $totalCount = $data. Conteggio                                          # BUCKET SUMMARY: Group by BucketId, show counts per bucket with Updated from global bucket stats                     if ($totalCount -gt 0) {                         $buckets = $data | Group-Object BucketId | Sort-Object -Decrescente                         $bucketSummary = "><2 h3 style='font-size:.95em; colore:#333; margin:10px 0 5px'><3 By Hardware Bucket ($($buckets. Count) bucket)><4 /h3>"                         $bucketSummary += "><6 div style='max-height:300px; overflow-y:auto; margin-bottom:15px'><table><thead><tr><th><5 BucketID><6 /th><th style='text-align:right'>Total</th><th style='text-align:right; color:#28a745'>Aggiornato</th><th style='text-align:right; colore:#dc3545 >non aggiornato</th><><1 produttore><2 /th></tr></thead><>"                         foreach ($b in $buckets) {                             $bid = if ($b.Name) { $b.Name } else { "(empty)" }                             $mfr = ($b.Gruppo | Select-Object -Primo 1). WMI_Manufacturer                             # Ottieni numero aggiornato dalle statistiche dei bucket globali (tutti i dispositivi in questo bucket nell'intero set di dati)                             $lookupKey = $bid                             $globalBucket = if ($stAllBuckets.ContainsKey($lookupKey)) { $stAllBuckets[$lookupKey] } else { $null }                             $bUpdatedGlobal = if ($globalBucket) { $globalBucket.Updated } else { 0 }                             $bTotalGlobal = if ($globalBucket) { $globalBucket.Count } else { $b.Count }                             $bNotUpdatedGlobal = $bTotalGlobal - $bUpdatedGlobal                             $bucketSummary += "<tr><td style='font-size:.8em'>$bid><4 /td><td style='text-align:right; font-weight:bold'>$bTotalGlobal><8 /td><td style='text-align:right; colore:#28a745; font-weight:bold'>$bUpdatedGlobal><2 /td><td style='text-align:right; colore:#dc3545; font-weight:bold'>$bNotUpdatedGlobal><6 /td><td><9 $mfr</td></tr>'n"                         }                         $bucketSummary += "</tbody></table></div>"                     }                                          # DEVICE DETAIL: Prime N righe come elenco piatto                     $slice = $data | Select-Object -First $MaxRows                     foreach ($d in $slice) {                         $conf = $d.ConfidenceLevel                         $confBadge = if ($conf -match "High") { '<span class="badge badge-success">High Conf><2 /span>' }                                      elseif ($conf -match "Not Sup") { '<span class="badge badge-danger">Non supportato><6 /span>' }                                      elseif ($conf -match "Under") { '<span class="badge-info">In Obs><0 /span>' }                                      elseif ($conf -match "Sospeso") { '<span class="badge-warning">Sospeso><4 /span>' }                                      else { '<span class="badge badge-warning">Action Req><8 /span>' }                         $statusBadge = if ($d.IsUpdated) { '><00 span class="badge badge-success"><01 Aggiornato</span>' }                                        elseif ($d.UEFICA2023Error) { '><04 span class="badge badge-danger"><05 Errore</span>' }                                        else { '><08 span class="badge badge-warning"><09 In sospeso><0 /span>' }                         $deviceRows += "><12 tr><td><5 $($d.HostName)><16 /td><td><9 $($d.WMI_Manufacturer)><20 /td><td><3 $($d.WMI_Model)><24 /td><td><7 $confBadge><8 /td><td><1 $statusBadge><2 /t><d><5 $(if($d.UEFICA2023Error){$d.UEFICA2023Error}else{'-'})><36 /td><td style='font-size:.75em'><39 $($d.BucketId)><40 /td></tr><3 'n"                     }                 } cattura { }             }             if ($totalCount -eq 0) {                 restituire "><44 div style='padding:20px; colore:#888; font-style:corsivo'><45 Nessun dispositivo in questa categoria.><46 /div>"             }             $showing = [matematica]::Min($MaxRows, $totalCount)             $header = "><48 div style='margin:5px 0; font-size:.85em; color:#666'><49 Total: $($totalCount.ToString("N0")) devices"             if ($CsvFileName) { $header += " | ><50 a href='$CsvFileName' style='color:#1a237e; font-weight:bold'>&#128196; Scarica file CSV completi per Excel><3 /a>" }             $header += "><55 /div>"             $deviceHeader = "><57 h3 style='font-size:.95em; colore:#333; margin:10px 0 5px'><58 Device Details (showing first $showing)><59 /h3>"             $deviceTable = "><61 div style='max-height:500px; overflow-y:auto'><tabella><thead><tr><th><0 HostName><1 /th><th><4 Manufacturer><5 /th><th><8 Model><9 /th><th><2 Confidence><3 /th><th><6 Status><7 /th><th><0 Error><1 /th><th><4 BucketId><5 /th></tr></thead><tbody><2 $deviceRows><3 /tbody></table></div>"             return "$header$bucketSummary$deviceHeader$deviceTable"         }                  # Crea tabelle inline dai file JSON già presenti sul disco, collegandoli a FILE CSV         $tblErrors = Build-InlineTable -JsonPath (Join-Path $dataDir "errors.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_errors_$timestamp.csv"         $tblKI = Build-InlineTable -JsonPath (Join-Path $dataDir "known_issues.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_known_issues_$timestamp.csv"         $tblKEK = Build-InlineTable -JsonPath (Join-Path $dataDir "missing_kek.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_missing_kek_$timestamp.csv"         $tblNotUpd = Build-InlineTable -JsonPath (Join-Path $dataDir "not_updated.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_not_updated_$timestamp.csv"         $tblTaskDis = Build-InlineTable -JsonPath (Join-Path $dataDir "task_disabled.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_task_disabled_$timestamp.csv"         $tblTemp = Build-InlineTable -JsonPath (Join-Path $dataDir "temp_failures.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_temp_failures_$timestamp.csv"         $tblPerm = Build-InlineTable -JsonPath (Join-Path $dataDir "perm_failures.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_perm_failures_$timestamp.csv"         $tblUpdated = Build-InlineTable -JsonPath (Join-Path $dataDir "updated_devices.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_updated_devices_$timestamp.csv"         $tblActionReq = Build-InlineTable -JsonPath (Join-Path $dataDir "action_required.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_action_required_$timestamp.csv"         $tblUnderObs = Build-InlineTable -JsonPath (Join-Path $dataDir "under_observation.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_under_observation_$timestamp.csv"         $tblNeedsReboot = Build-InlineTable -JsonPath (Join-Path $dataDir "needs_reboot.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_needs_reboot_$timestamp.csv"         $tblSBOff = Build-InlineTable -JsonPath (Join-Path $dataDir "secureboot_off.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_secureboot_off_$timestamp.csv"         $tblRolloutIP = Build-InlineTable -JsonPath (Join-Path $dataDir "rollout_inprogress.json") -MaxRows $maxInlineRows -CsvFileName "SecureBoot_rollout_inprogress_$timestamp.csv"         # Custom table for Update Pending — includes UEFICA2023Status and UEFICA2023Error columns         $tblUpdatePending = ""         $upJsonPath = Join-Path $dataDir "update_pending.json"         if (Test-Path $upJsonPath) {             prova {                 $upData = Get-Content $upJsonPath -Raw | ConvertFrom-Json                 $upCount = $upData.Count                 if ($upCount -gt 0) {                     $upHeader = "<div style='margin:5px 0; font-size:.85em; color:#666'>Totale: dispositivi $($upCount.ToString("N0")) | <a href='SecureBoot_update_pending_$timestamp.csv' style='color:#1a237e; font-weight:bold'>&#128196; Scaricare file CSV completi per Excel><4 /a></div>"                     $upRows = ""                     $upSlice = $upData | Select-Object -First $maxInlineRows                     foreach ($d in $upSlice) {                         $uefiSt = if ($d.UEFICA2023Status) { $d.UEFICA2023Status } else { '<span style="color:#999">null><0 /span>' }                         $uefiErr = if ($d.UEFICA2023Error) { "<span style='color:#dc3545'>$($d.UEFICA2023Error)</span>" } else { '-' }                         $policyVal = if ($d.AvailableUpdatesPolicy) { $d.AvailableUpdatesPolicy } else { '-' }                         $wincsVal = if ($d.WinCSKeyApplied) { '<span class="badge badge-success">Sì><8 /span>' } else { '-' }                         $upRows += "<tr><td><3 $($d.HostName)</td><td><7 $($d.WMI_Manufacturer)</td><td><1 $($d.WMI_Model)</td><t><5 $uefiSt><6 /td><td><9 $uefiErr><50 /td><td><53 $policyVal><54 /td><td><57 $wincsVal><58 /td><td style='font-size:.75em'>$($d.BucketId)</td></tr><65 'n"                     }                     $upShowing = [matematica]::Min($maxInlineRows, $upCount)                     $upDevHeader = "<h3 style='font-size:.95em; colore:#333; margin:10px 0 5px'>Device Details (showing first $upShowing)</h3>"                     $upTable = "<div style='max-height:500px; overflow-y:auto'><tabella><thead><tr><th><9 HostName><0 /th><th><3 Manufacturer><4 /th th><><7 Model><8 /th><><1 UEFICA2023Status><2 /th><><5 UEFICA2023Error><6 /th><th><9 Policy</th><>tasto WinCS</th><>BucketId</th></tr></thead><tbody><5 $upRows><6 /tbody></table></div>"                     $tblUpdatePending = "$upHeader$upDevHeader$upTable"                 } else {                     $tblUpdatePending = "<div style='padding:20px; colore:#888; font-style:corsivo'>Nessun dispositivo in questa categoria.</div>"                 }             } catch {                 $tblUpdatePending = "<div style='padding:20px; colore:#888; font-style:corsivo'>Nessun dispositivo in questa categoria.</div>"             }         } else {             $tblUpdatePending = "<div style='padding:20px; colore:#888; font-style:corsivo'>Nessun dispositivo in questa categoria.</div>"         }                  # Conto alla rovescia per la scadenza del certificato         $certToday = Get-Date         $certKekExpiry = [datetime]"2026-06-24"         $certUefiExpiry = [datetime]"2026-06-27"         $certPcaExpiry = [datetime]"2026-10-19"         $daysToKek = [matematica]::Max(0; ($certKekExpiry - $certToday). Giorni)         $daysToUefi = [matematica]::Max(0, ($certUefiExpiry - $certToday). Giorni)         $daysToPca = [matematica]::Max(0, ($certPcaExpiry - $certToday). Giorni)         $certUrgency = if ($daysToKek -lt 30) { '#dc3545' } elseif ($daysToKek -lt 90) { '#fd7e14' } else { '#28a745' }                  # Build manufacturer chart data inline (Top 10 per numero di dispositivi)         $mfrSorted = $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Decrescente | Select-Object -First 10         $mfrChartTitle = if ($stMfrCounts.Count -le 10) { "By Manufacturer" } else { "Top 10 Manufacturers" }         $mfrLabels = ($mfrSorted | ForEach-Object { "'$($_. Key)'" }) -join ","         $mfrUpdated = ($mfrSorted | ForEach-Object { $_. Value.Updated }) -join ","         $mfrUpdatePending = ($mfrSorted | ForEach-Object { $_. Value.UpdatePending }) -join ","         $mfrHighConf = ($mfrSorted | ForEach-Object { $_. Value.HighConf }) -join ","         $mfrUnderObs = ($mfrSorted | ForEach-Object { $_. Value.UnderObs }) -join ","         $mfrActionReq = ($mfrSorted | ForEach-Object { $_. Value.ActionReq }) -join ","         $mfrTempPaused = ($mfrSorted | ForEach-Object { $_. Value.TempPaused }) -join ","         $mfrNotSupported = ($mfrSorted | ForEach-Object { $_. Value.NotSupported }) -join ","         $mfrSBOff = ($mfrSorted | ForEach-Object { $_. Value.SBOff }) -join ","         $mfrWithErrors = ($mfrSorted | ForEach-Object { $_. Value.WithErrors }) -join ","                  Tabella del produttore della build #         $mfrTableRows = ""         $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Decrescente | ForEach-Object {             $mfrTableRows += "<tr><td><7 $($_. chiave)</td><td>$($_. Value.Total.ToString("N0"))</td><td>$($_. Value.Updated.ToString("N0"))</td><td>$($_. Value.HighConf.ToString("N0"))><0 /td><td>$($_. Value.ActionReq.ToString("N0"))><4 /td></tr>'n"         }                  $htmlContent = @" <!> HTML DOCTYPE <html lang="en"> ><3 testa < <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <titolo><9 dashboard di stato del certificato di avvio protetto><0 /title><1 <script src="https://cdn.jsdelivr.net/npm/chart.js"></script><5 ><7 di stile < *{box-sizing:border-box; margine:0; spaziatura interna:0} body{font-family:'Segoe UI',Tahoma,sans-serif; sfondo:#f0f2f5; colore:#333} .header{background:linear-gradient(135deg,#1a237e,#0d47a1); colore:#fff; spaziatura interna:20px 30px} .header h1{font-size:1.6em; margin-bottom:5px} .header .meta{font-size:.85em; opacità:.9} .container{max-width:1400px; margine:0 auto; spaziatura interna:20px} .cards{display:grid; grid-template-columns:repeat(auto-fill,minmax(170px,1fr)); gap:12px; margine:20px 0} .card{background:#fff; border-radius:10px; riempimento:15px; box-shadow:0 2px 8px rgba(0,0,0,08); bordo-sinistra:4px solid #ccc;transition:transform .2s} .card:hover{transform:translateY(-2px); ombreggiatura:0 4px 15px rgba(0,0,0,12)} .card .value{font-size:1.8em; font-weight:700} .card .label{font-size:.8em; colore:#666; margin-top:4px} .card .pct{font-size:.75em; colore:#888} .section{background:#fff; border-radius:10px; riempimento:20px; margine:15px 0; ombreggiatura:0 2px 8px rgba(0,0,0,08)} .section h2{font-size:1.2em; colore:#1a237e; margin-bottom:10px; cursor:pointer; user-select:none} .section h2:hover{text-decoration:underline} .section-body{display:none} .section-body.open{display:block} .charts{display:grid; grid-template-columns:1fr 1fr; gap:20px; margine:20px 0} chart-box{background:#fff; border-radius:10px; riempimento:20px; ombreggiatura:0 2px 8px rgba(0,0,0,08)} tabella{width:100%; border-collapse:collapse; dimensione carattere:.85em} th{background:#e8eaf6; riempimento:8px 10px; testo-allinea:sinistra; posizione:appiccicoso; superiore:0; z-index:1} td{padding:6px 10px; bordo-inferiore:1px #eee} tr:hover{background:#f5f5f5} .badge{display:inline-block; spaziatura:2px 8px;border-radius:10px; dimensione carattere:.75em; font-weight:700} .badge-success{background:#d4edda; color:#155724} .badge-danger{background:#f8d7da; colore:#721c24} .badge-warning{background:#fff3cd; color:#856404} .badge-info{background:#d1ecf1; colore:#0c5460} .top-link{float:right; dimensione carattere:.8em; colore:#1a237e; text-decoration:none} .footer{text-align:center; riempimento:20px; colore:#999; dimensione carattere:.8em} a{color:#1a237e} </style><9 >/head < >corpo < <div class="header">     <h1>dashboard di stato del certificato di avvio protetto</h1>     <div class="meta">Generated: $($stats. ReportGeneratedAt) | Totale dispositivi: $($c.Total.ToString("N0")) | Contenitori univoci: $($stAllBuckets.Count)</div><3 ><5 /div < <div class="container">

<!-- schede KPI- selezionabili, collegate a sezioni --> <div class="cards">     <a class="card" href="#s-nu" onclick="openSection('d-nu')" style="border-left-color:#dc3545; text-decoration:none; position:relative"><div style="position:absolute; top:8px; destra:8px; sfondo:#dc3545; colore:#fff; riempimento:1px 6px; border-radius:8px; dimensione carattere:.65em; font-weight:700">PRIMARY</div><div class="value" style="color:#dc3545">$($stNotUptodate.ToString("N0"))</div><div class="label">NOT UPDATED><6 /div><div class="pct">$($stats. PercentNotUptodate)% - NEEDS ACTION><0 /div></a><3     <a class="card" href="#s-upd" onclick="openSection('d-upd')" style="border-left-color:#28a745; text-decoration:none; position:relative"><div style="position:absolute; top:8px; destra:8px; sfondo:#28a745; colore:#fff; riempimento:1px 6px; border-radius:8px; dimensione carattere:.65em; font-weight:700">PRIMARY><8 /div><div class="value" style="color:#28a745">$($c.Updated.ToString("N0"))</div><div class="label">Aggiornato><6 /div><div class="pct">$($stats. PercentCertUpdated)%</div></a><3     <a class="card" href="#s-sboff" onclick="openSection('d-sboff')" style="border-left-color:#6c757d; text-decoration:none; position:relative"><div style="position:absolute; top:8px; destra:8px; sfondo:#6c757d; colore:#fff; riempimento:1px 6px; border-radius:8px; dimensione carattere:.65em; font-weight:700">PRIMARY><8 /div><div class="value"><1 $($c.SBOff.ToString("N0"))><2 /div><div class="label"><5 SecureBoot OFF</div><div class="pct"><9 $(if($c.Total -gt 0){[math]::Round(($c.SBOff/$c.Total)*100,1)}else{0})% - Out of Scope><0 /div></a><3     <a class="card" href="#s-nrb" onclick="openSection('d-nrb')" style="border-left-color:#ffc107; text-decoration:none"><div class="value" style="color:#ffc107">$($c.NeedsReboot.ToString("N0"))</div><div class="label">Needs Reboot><2 /div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.NeedsReboot/$c.Total)*100,1)}else{0})% - in attesa di riavvio><6 /div></a><9     <a class="card" href="#s-upd-pend" onclick="openSection('d-upd-pend')" style="border-left-color:#6f42c1; text-decoration:none"><div class="value" style="color:#6f42c1">$($c.UpdatePending.ToString("N0"))</div><div class="label">Update Pending</div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.UpdatePending/$c.Total)*100,1)}else{0})% - Policy/WinCS applicato, in attesa di aggiornamento><2 /div></a><5     <a class="card" href="#s-rip" onclick="openSection('d-rip')" style="border-left-color:#17a2b8; text-decoration:none"><div class="value">$($c.RolloutInSensi)</div><div class="label">Rollout In corso><4 /div><div class="pct ">$(if($c.Total -gt 0){[math]::Round(($c.RolloutIn Applaus/$c.Total)*100,1)}else{0})%</div></a><11     <a class="card" href="#s-nu" onclick="openSection('d-nu')" style="border-left-color:#28a745; text-decoration:none"><div class="value" style="color:#28a745">$($c.HighConf.ToString("N0"))</div><div class="label">High Confidence><20 /div><div class="pct">$($stats. PercentHighConfidence)% - Sicuro per l'implementazione><24 /div></a><27     <a class="card" href="#s-uo" onclick="openSection('d-uo')" style="border-left-color:#17a2b8; text-decoration:none"><div class="value" style="color:#ffc107"><1 $($c.UnderObs.ToString("N0"))><2 /div><div class="label"><5 Under Observation><36 /div><div class="pct"><9 $(if($c.Total -gt 0){[math]::Round(($c.UnderObs/$c.Total)*100,1)}else{0})%</div></a><3     <a class="card" href="#s-ar" onclick="openSection('d-ar')" style="border-left-color:#fd7e14; text-decoration:none"><div class="value" style="color:#fd7e14">$($c.ActionReq.ToString("N0"))</div><div class="label">Action Required><2 /div><div class="pct">$($stats. PercentActionRequired)% - deve testare><6 /div></a><9     <a class="card" href="#s-err" onclick="openSection('d-err')" style="border-left-color:#dc3545; text-decoration:none"><div class="value" style="color:#dc3545">$($stAtRisk.ToString("N0"))</div><div class="label">At Risk><68 /div><div class="pct">$($stats. PercentAtRisk)% - Simile all'errore><2 /div></a><5     <a class="card" href="#s-td" onclick="openSection('d-td')" style="border-left-color:#dc3545; text-decoration:none"><div class="value" style="color:#dc3545">$($c.TaskDisabled.ToString("N0"))</div><div class="label">Task Disabled><4 /div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.TaskDisabled/$c.Total)*100,1)}else{0})% - Blocked><8 /div></a><91     <a class="card" href="#s-tf" onclick="openSection('d-tf')" style="border-left-color:#fd7e14; text-decoration:none"><div class="value" style="color:#fd7e14">$($c.TempPaused.ToString("N0"))</div><div class="label">Temp. Sospeso</div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.TempPaused/$c.Total)*100,1)}else{0})%</div></a>     <a class="card" href="#s-ki" onclick="openSection('d-ki')" style="border-left-color:#dc3545; text-decoration:none"><div class="value" style="color:#dc3545">$($c.WithKnownIssues.ToString("N0"))</div><div class="label">Known Issues><6 /div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.WithKnownIssues/$c.Total)*100,1)}else{0})%</div></a><3     <a class="card" href="#s-kek" onclick="openSection('d-kek')" style="border-left-color:#fd7e14; text-decoration:none"><div class="value" style="color:#fd7e14">$($c.WithMissingKEK.ToString("N0"))</div><div class="label">KEK mancante</div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.WithMissingKEK/$c.Total)*100,1)}else{0})%</div></a>     <a class="card" href="#s-err" onclick="openSection('d-err')" style="border-left-color:#dc3545; text-decoration:none"><div class="value" style="color:#dc3545">$($c.WithErrors.ToString("N0"))</div><div class="label">With Errors</div><div class="pct"><1 $($stats. PercentWithErrors)% - Errori UEFI</div></a>     ><6 a class="card" href="#s-tf" onclick="openSection('d-tf')" style="border-left-color:#dc3545; text-decoration:none"><div class="value" style="color:#dc3545"><9 $($c.TempFailures.ToString("N0"))</div><div class="label">Temp. Errori</div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.TempFailures/$c.Total)*100,1)}else{0})%</div></a>     <a class="card" href="#s-pf" onclick="openSection('d-pf')" style="border-left-color:#721c24; text-decoration:none"><div class="value" style="color:#721c24">$($c.PermFailures.ToString("N0"))</div><div class="label">Not Supported><6 /div><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.PermFailures/$c.Total)*100,1)}else{0})%</div></a><3 </di> v

velocità di distribuzione<!-- & scadenza del certificato --> <div id="s-velocity" style="display:grid; grid-template-columns:1fr 1fr; gap:20px; margin:15px 0"> <div class="section" style="margin:0">     <h2>&#128197;>velocità di distribuzione< /h2     <div class="section-body open">         <div style="font-size:2.5em; font-weight:700; color:#28a745">$($c.Updated.ToString("N0"))</div>         <div style="color:#666">dispositivi aggiornati su $($c.Total.ToString("N0"))</div>         <div style="margin:10px 0; sfondo:#e8eaf6; altezza:20px; border-radius:10px; overflow:hidden"><div style="background:#28a745; altezza:100%; width:$($stats. PercentCertUpdated)%; border-radius:10px"></div></div>         <div style="font-size:.8em; color:#888">$($stats. PercentCertUpdated)% completamento</div>         <div style="margin-top:10px; riempimento:10px; sfondo:#f8f9fa; border-radius:8px; font-size:.85em">             <div><dispositivi>rimanenti:</strong> $($stNotUptodate.ToString("N0")) richiedono l'intervento</div>             <div><blocco>forte:</strong> dispositivi $($c.WithErrors + $c.PermFailures + $c.TaskDisabledNotUpdated) (errori + permanente + attività disabilitata)</div>             <div><dispositivi con>sicuro da distribuire:</strong> dispositivi con estensione $($stSafeList.ToString("N0")) </div>             $velocityHtml        >/div <    >/div < >/div < <div class="section" style="margin:0; bordo-sinistra:4px #dc3545 a tinta unita">     <h2 style="color:#dc3545">&#9888; Certificate Expiry Countdown</h2>     <div class="section-body open">         <div style="display:flex; gap:15px; margin-top:10px">             <div style="text-align:center; riempimento:15px; border-radius:8px; min-width:120px; sfondo:sfumatura lineare(135 gradi;#fff5f5;#ffe0e0); border:2px solid #dc3545; flex:1">                 <div style="font-size:.65em; colore:#721c24; text-transform:uppercase; font-weight:bold">&#9888; FIRST TO EXPIRE</div>                 ><4 div style="font-size:.85em; font-weight:bold; colore:#dc3545; margin:3px 0"><5 KEK CA 2011</div>                 ><8 div id="daysKek" style="font-size:2.5em; font-weight:700; colore:#dc3545; altezza linea:1"><9 $daysToKek</div>                 ><2 div style="font-size:.8em; colore:#721c24"><3 giorni (24 giugno 2026)><4 /div>            >/div ><6             ><8 div style="text-align:center; riempimento:15px; border-radius:8px; min-width:120px; sfondo:sfumatura lineare(135 gradi,#fffef5,#fff3cd); border:2px solid #ffc107; flex:1"><9                 <div style="font-size:.65em; color:#856404; text-transform:uppercase; font-weight:bold">UEFI CA 2011</div>                 <div id="daysUefi" style="font-size:2.2em; font-weight:700; color:#856404; altezza linea:1; margin:5px 0">$daysToUefi</div>                 <div style="font-size:.8em; color:#856404">giorni (27 giugno 2026)</div>            >/div <             <div style="text-align:center; riempimento:15px; border-radius:8px; min-width:120px; sfondo:sfumatura lineare(135 gradi,#f0f8ff,#d4edff); border:2px solid #0078d4; flex:1">                 <div style="font-size:.65em; colore:#0078d4; text-transform:uppercase; font-weight:bold">PCA Windows</div>                 <div id="daysPca" style="font-size:2.2em; font-weight:700; colore:#0078d4; altezza linea:1; margin:5px 0">$daysToPca><2 /div><3                 <div style="font-size:.8em; colore:#0078d4">giorni (19 ottobre 2026)</div><7            ><9 /div <        ><1 /div <         <div style="margin-top:15px; riempimento:10px; sfondo:#f8d7da; border-radius:8px; font-size:.85em; bordo-sinistra:#dc3545 a tinta unita 4px">             <strong>&#9888; CRITICAL:</strong> Tutti i dispositivi devono essere aggiornati prima della scadenza del certificato. I dispositivi non aggiornati entro la scadenza non possono applicare futuri aggiornamenti della sicurezza per Boot Manager e avvio protetto dopo la scadenza.>/div <    >/div < >/div < > /div <

grafici<!-- -> <div class="charts">     <div class="chart-box"><h3>Stato distribuzione</h3><canvas id="deployChart" height="200"></canvas></div><5     <div class="chart-box"><h3><9 $mfrChartTitle</h3><canvas id="mfrChart" height="200"></canvas></div> > /div <

$(if ($historyData.Count -ge 1) { "<!-- Grafico di tendenza cronologico - > <div class='section'>     <h2 onclick='"toggle('d-trend')'">&#128200; Update Progress Over Time <a class='top-link' href='#'>&#8593; Top</a></h2>     <div id='d-trend' class='section-body open'>         <canvas id='trendChart' height='120'></canvas>         <div style='font-size:.75em; colore:#888; margin-top:5px'>Linee continue = dati effettivi$(if ($historyData.Count -ge 2) { " | Linea tratteggiata = proiezione (raddoppiamento esponenziale: 2&#x2192;4&#x2192;8&#x2192;16... dispositivi per onda)" } else { " | Eseguire di nuovo l'aggregazione domani per visualizzare le linee di tendenza e la proiezione" })</div>    >/div < > /div <" })

Download di file CSV<!-- - > <div class="section">     <h2 onclick="toggle('dl-csv')">&#128229; Scaricare dati completi (CSV per Excel) <a class="top-link" href="#">Top</a></h2><2     <div id="dl-csv" class="section-body open" style="display:flex; flex-wrap:wrap; gap:5px">         <a href="SecureBoot_not_updated_$timestamp.csv" style="display:inline-block; sfondo:#dc3545; colore:#fff; riempimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Not Updated ($($stNotUptodate.ToString("N0")))</a><8         <a href="SecureBoot_errors_$timestamp.csv" style="display:inline-block; sfondo:#dc3545; colore:#fff; riempimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Errors ($($c.WithErrors.ToString("N0")))</a>         <a href="SecureBoot_action_required_$timestamp.csv" style="display:inline-block; sfondo:#fd7e14; colore:#fff; riempimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Action Required ($($c.ActionReq.ToString("N0")))</a>         <a href="SecureBoot_known_issues_$timestamp.csv" style="display:inline-block; sfondo:#dc3545; colore:#fff; riempimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">problemi noti ($($c.WithKnownIssues.ToString("N0")))</a>         <a href="SecureBoot_task_disabled_$timestamp.csv" style="display:inline-block; sfondo:#dc3545; colore:#fff; riempimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Task Disabled ($($c.TaskDisabled.ToString("N0")))</a>         <a href="SecureBoot_updated_devices_$timestamp.csv" style="display:inline-block; sfondo:#28a745; colore:#fff; riempimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Updated ($($c.Updated.ToString("N0")))</a>         <a href="SecureBoot_Summary_$timestamp.csv" style="display:inline-block; sfondo:#6c757d; colore:#fff; riempimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Summary</a>         <div style="width:100%; dimensione carattere:.75em; colore:#888; margin-top:5px">file CSV aperti in Excel. Disponibile in server.</div>    >/div < > /div <

<!-- suddivisione del produttore -- > <div class="section">     <h2 onclick="toggle('mfr')">By Manufacturer <a class="top-link" href="#">Top</a></h2><1     <div id="mfr" class="section-body open">     <tabella><><><><1 produttore><2><><5 totale><6/><><9 aggiornate><6><0><><3 alta confidenza><4><><7 azione necessaria><8 /th></tr></thead><3     <><5 $mfrTableRows><6 /tbody></table><9    ><1 /div < > /div <

<!-- sezioni del dispositivo (primo download 200 in linea + CSV) --> <div class="section" id="s-err">     <h2 onclick="toggle('d-err')">&#128308; Dispositivi con errori ($($c.WithErrors.ToString("N0"))) <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-err" class="section-body">$tblErrors</div> >/div < <div class="section" id="s-ki">     <h2 onclick="toggle('d-ki')" style="color:#dc3545">&#128308; Problemi noti ($($c.WithKnownIssues.ToString("N0"))) <un class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-ki" class="section-body">$tblKI</div> >/div < <div class="section" id="s-kek">     <h2 onclick="toggle('d-kek')">&#128992; KEK mancante - Evento 1803 ($($c.WithMissingKEK.ToString("N0"))) <un class="top-link" href="#">&#8593; Top</a></h2>     >&#8593; 0 div id="d-kek" class="section-body">&#8593; 1 $tblKEK</div> >/div >&#8593; 4 >&#8593; 6 div class="section" id="s-ar">&#8593; 7     >&#8593; 8 h2 onclick="toggle('d-ar')" style="color:#fd7e14">&#128992; Azione richiesta ($($c.ActionReq.ToString("N0"))) <a class="top-link" href="#">&#8593; Top><4 /a></h2><7     <div id="d-ar" class="section-body">$tblActionReq</div> >/div < <div class="section" id="s-uo">     <h2 onclick="toggle('d-uo')" style="color:#17a2b8">&#128309; In Osservazione ($($c.UnderObs.ToString("N0"))) <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-uo" class="section-body">$tblUnderObs</div> >/div < <div class="section" id="s-nu">     <h2 onclick="toggle('d-nu')" style="color:#dc3545">&#128308; Non aggiornato ($($stNotUptodate.ToString("N0"))) <class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-nu" class="section-body">$tblNotUpd</div> >/div < >&#8593; 0 div class="section" id="s-td">&#8593; 1     >&#8593; 2 h2 onclick="toggle('d-td')" style="color:#dc3545">&#128308; Attività disabilitata ($($c.TaskDisabled.ToString("N0"))) >&#8593; 5 a class="top-link" href="#">&#8593; Top</a></h2><1     <div id="d-td" class="section-body">$tblTaskDis><4 /div><5 ><7 /div < <div class="section" id="s-tf">     <h2 onclick="toggle('d-tf')" style="color:#dc3545">&#128308; Errori temporanei ($($c.TempFailures.ToString("N0"))) <class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-tf" class="section-body">$tblTemp</div> >/div < <div class="section" id="s-pf">     <h2 onclick="toggle('d-pf')" style="color:#721c24">&#128308; Errori permanenti/Non supportati ($($c.PermFailures.ToString("N0"))) <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-pf" class="section-body">$tblPerm</div> >/div < <div class="section" id="s-upd-pend">     <h2 onclick="toggle('d-upd-pend')" style="color:#6f42c1">&#9203; Update Pending ($($c.UpdatePending.ToString("N0"))) - Criteri/WinCS applicati, In attesa di Aggiornamento <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-upd-pend" class="section-body"><p style="color:#666; margin-bottom:10px">Dispositivi in cui è applicata la chiave AvailableUpdatesPolicy o WinCS, ma UEFICA2023Status è ancora NotStarted,Ino o Null.</p>$tblUpdatePending</div> >/div < <div class="section" id="s-rip">     <h2 onclick="toggle('d-rip')" style="color:#17a2b8">&#128309; Implementazione in corso ($($c.RolloutIn Progress.ToString("N0"))) <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-rip" class="section-body">$tblRolloutIP</div> >/div < <div class="section" id="s-sboff">     <h2 onclick="toggle('d-sboff')" style="color:#6c757d">&#9899; SecureBoot OFF ($($c.SBOff.ToString("N0"))) - Out of Scope <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-sboff" class="section-body">$tblSBOff</div> >/div < <div class="section" id="s-upd">     <h2 onclick="toggle('d-upd')" style="color:#28a745">&#128994; Dispositivi aggiornati ($($c.Updated.ToString("N0"))) <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-upd" class="section-body">$tblUpdated</div> >/div < <div class="section" id="s-nrb">     <h2 onclick="toggle('d-nrb')" style="color:#ffc107">&#128260; Aggiornato: è necessario riavviare ($($c.NeedsReboot.ToString("N0"))) <a class="top-link" href="#">&#8593; Top</a></h2>     <div id="d-nrb" class="section-body">$tblNeedsReboot</div> > /div <

<div class="footer">Secure Boot Certificate Rollout Dashboard | $($stats) generato. ReportGeneratedAt) | StreamingMode | Memoria di picco: ${stPeakMemMB} MB</div> </div><!-- /container -->

>script< function toggle(id){var e=document.getElementById(id); e.classList.toggle('open')} funzione openSection(id){var e=document.getElementById(id); if(e&&!e.classList.contains('open')){e.classList.add('open')}} new Chart(document.getElementById('deployChart'),{type:'doughnut',data:{labels:['Updated','Update Pending','High Confidence','Under Observation','Action Required','Temp. In pausa','Non supportato','SecureBoot OFF','With Errors'],datasets:[{data:[$($c.Updated),$($c.UpdatePending),$($c.HighConf),$($c.UnderObs),$($c.ActionReq),$($c.TempPaused),$($c.NotSupported),$($c.SBOff),$($c.NotSupported)$($c.SBOff),$($c.WithErrors)],backgroundColor:['#28a745','#6f42c1','#20c997','#17a2b8','#fd7e14','#6c757d','#721c24 #6c757d','#17a2b8'','#adb5bd','#dc3545']}]},options:{responsive:true,plugins:{legend:{position:'right',labels:{font:{size:11}}}}}}); new Chart(document.getElementById('mfrChart'),{type:'bar',data:{labels:[$mfrLabels],datasets:[{label:'Updated',data:[$mfrUpdated],backgroundColor:'#28a745'},{label:'Update Pending',data:[$mfrUpdatePending],backgroundColor:'#6f42c1 '},{label:'High Confidence',data:[$mfrHighConf],backgroundColor:'#20c997'},{label:'Under Observation',data:[$mfrUnderObs],backgroundColor:'#17a2b8'},{label:'Action Required',data:[$mfrActionReq],backgroundColor:'#fd7e14'},{ label:'Temp. Sospeso',dati:[$mfrTempPaused],backgroundColor:'#6c757d'},{label:'Non supportato',dati:[$mfrNotSupported],backgroundColor:'#721c24'},{label:'SecureBoot OFF',data:[$mfrSBOff],backgroundColor:'#adb5bd'}},{label:'With Errors',data:[$mfrWithErrors],backgroundColor:'#dc3545'}]},options:{responsive:true,scales:{x:{stacked:true},y:{stacked:true}},plugins:{legend:{position:'top'}}}}); Grafico di tendenza cronologico if (document.getElementById('trendChart')) { var allLabels = [$allChartLabels]; var actualUpdated = [$trendUpdated]; var actualNotUpdated = [$trendNotUpdated]; var actualTotal = [$trendTotal]; var projData = [$projDataJS]; var projNotUpdData = [$projNotUpdJS]; var histLen = actualUpdated.length; var projLen = projData.length; var paddedUpdated = actualUpdated.concat(Array(projLen).fill(null)); var paddedNotUpdated = actualNotUpdated.concat(Array(projLen).fill(null)); var paddedTotal = actualTotal.concat(Array(projLen).fill(Null)); var projLine = Array(histLen).fill(null); var projNotUpdLine = Array(histLen).fill(null); if (projLen > 0) { projLine[histLen-1] = actualUpdated[histLen-1]; projLine = projLine.concat(projData); projNotUpdLine[histLen-1] = actualNotUpdated[histLen-1]; projNotUpdLine = projNotUpdLine.concat(projNotUpdData); } set di dati var = [     {label:'Updated',data:paddedUpdated,borderColor:'#28a745',backgroundColor:'rgba(40,167,69,0.1)',fill:true,tension:0.3,borderWidth:2},     {label:'Non aggiornato',data:paddedNotUpdated,borderColor:'#dc3545',backgroundColor:'rgba(220,53,69,0.1)',fill:true,tension:0.3,borderWidth:2},     {label:'Total',data:paddedTotal,borderColor:'#6c757d',borderDash:[5,5],fill:false,tension:0,pointRadius:0,borderWidth:1} ]; if (projLen > 0) {     datasets.push({label:'Projected Updated (2x doubling)',data:projLine,borderColor:'#28a745',borderDash:[8,4],borderWidth:3,fill:false,tension:0.3,pointRadius:3,pointStyle:'triangle'});     datasets.push({label:'Projected Not Updated',data:projNotUpdLine,borderColor:'#dc3545',borderDash:[8,4],borderWidth:3,fill:false,tension:0.3,pointRadius:3,pointStyle:'triangle'}); } new Chart(document.getElementById('trendChart'),{type:'line',data:{labels:allLabels,datasets:datasets},options:{responsive:true,scales:{y:{beginAtZero:true,title:{display:true,text:'Devices'}},x:{title:{display:true,text:'Date'}}},plugins:{legend:{position:'top'},title:{display:true,text:'Secure Boot Update Progress Over Time'}}}}); } Conto alla rovescia dinamico (function(){var t=new Date(),k=new Date('2026-06-24'),u=new Date('2026-06-27'),p=new Date('2026-10-19'); var dk=document.getElementById('daysKek'),du=document.getElementById('daysUefi'),dp=document.getElementById('daysPca'); if(dk)dk.textContent=Math.max(0,Math.ceil((k-t)/864e5)); if(du)du.textContent=Math.max(0,Math.ceil((u-t)/864e5)); if(dp)dp.textContent=Math.max(0,Math.ceil((p-t)/864e5)})(); </script> >/body < >/html < "@         [System.IO.File]::WriteAllText($htmlPath, $htmlContent, [System.Text.UTF8Encoding]::new($false))         # Conserva sempre una copia stabile "Ultima" in modo che gli amministratori non debbano tenere traccia dei timestamp         $latestPath = Join-Path $OutputPath "SecureBoot_Dashboard_Latest.html"         Copy-Item $htmlPath $latestPath -Force         $stTotal = $streamSw.Elapsed.TotalSeconds         # Salvare il manifesto del file per la modalità incrementale (rilevamento rapido senza modifiche alla successiva esecuzione)         if ($IncrementalMode -or $StreamingMode) {             $stManifestDir = Join-Path $OutputPath ".cache"             if (-not (Test-Path $stManifestDir)) { New-Item -ItemType Directory -Path $stManifestDir -Force | Out-Null }             $stManifestPath = Join-Path $stManifestDir "StreamingManifest.json"             $stNewManifest = @{}             Write-Host "Salvataggio del manifesto file per la modalità incrementale..." -ForegroundColor Gray             foreach ($jf in $jsonFiles) {                 $stNewManifest[$jf. FullName.ToLowerInvariant()] = @{                     LastWriteTimeUtc = $jf. LastWriteTimeUtc.ToString("o")                     Dimensione = $jf. Lunghezza                 }             }             Save-FileManifest -Manifest $stNewManifest -Path $stManifestPath             Write-Host " Manifest salvato per file $($stNewManifest.Count)" -ForegroundColor DarkGray         }         # PULIZIA CONSERVAZIONE         # Cartella riutilizzabile orchestrazione (Aggregation_Current): mantieni solo l'ultima esecuzione (1)         # Amministrazione le esecuzioni manuali / altre cartelle: mantieni le ultime 7 esecuzioni         # I CSV di riepilogo non vengono MAI eliminati: sono minuscoli (~1 KB) e sono l'origine di backup per la cronologia delle tendenze         $outputLeaf = Split-Path $OutputPath -Leaf         $retentionCount = if ($outputLeaf -eq 'Aggregation_Current') { 1 } else { 7 }         # Prefissi file sicuri da pulire (snapshot effimeri per ogni esecuzione)         $cleanupPrefixes = @(             "SecureBoot_Dashboard_",             'SecureBoot_action_required_',             "SecureBoot_ByManufacturer_",             "SecureBoot_ErrorCodes_",             'SecureBoot_errors_',             'SecureBoot_known_issues_',             "SecureBoot_missing_kek_",             'SecureBoot_needs_reboot_',             "SecureBoot_not_updated_",             'SecureBoot_secureboot_off_',             "SecureBoot_task_disabled_",             'SecureBoot_temp_failures_',             'SecureBoot_perm_failures_',             'SecureBoot_under_observation_',             'SecureBoot_UniqueBuckets_',             'SecureBoot_update_pending_',             'SecureBoot_updated_devices_',             "SecureBoot_rollout_inprogress_",             'SecureBoot_NotUptodate_',             'SecureBoot_Kusto_'         )         # Trova tutti i timestamp univoci solo da file pulibili         $cleanableFiles = Get-ChildItem $OutputPath -File -EA SilentlyContinue |             Where-Object { $f = $_. Nome; ($cleanupPrefixes | Where-Object { $f.StartsWith($_) }). Count -gt 0 }         $allTimestamps = @($cleanableFiles | ForEach-Object {             if ($_. Name -match '(\d{8}-\d{6})') { $Matches[1] }         } | Sort-Object -Univoco -Decrescente)         if ($allTimestamps.Count -gt $retentionCount) {             $oldTimestamps = $allTimestamps | Select-Object -Salta $retentionCount             $removedFiles = 0; $freedBytes = 0             foreach ($oldTs in $oldTimestamps) {                 foreach ($prefix in $cleanupPrefixes) {                     $oldFiles = Get-ChildItem $OutputPath -File -Filter "${prefix}${oldTs}*" -EA SilentlyContinue                     foreach ($f in $oldFiles) {                         $freedBytes += $f.Length                         Remove-Item $f.FullName -Force -EA SilentlyContinue                         $removedFiles++                     }                 }             }             $freedMB = [math]::Round($freedBytes / 1MB, 1)             Write-Host "Pulizia conservazione: rimosso $removedFiles file da $($oldTimestamps.Count) vecchie esecuzioni, liberato ${freedMB} MB (mantenendo l'ultimo $retentionCount + tutti i FILE CSVs di riepilogo/NotUptodate)" -ForegroundColor DarkGray         }         Write-Host "'n$("=" * 60)" -ForegroundColor Ciano         Write-Host "AGGREGAZIONE STREAMING COMPLETATA" -ForegroundColor green         Write-Host ("=" * 60) -ForegroundColor Ciano         Write-Host " Total Devices: $($c.Total.ToString("N0"))" -ForegroundColor White         Write-Host " NOT UPDATED: $($stNotUptodate.ToString("N0")) ($($stats. PercentNotUptodate)%)" -ForegroundColor $(if ($stNotUptodate -gt 0) { "Yellow" } else { "Green" })         Write-Host " Updated: $($c.Updated.ToString("N0")) ($($stats. PercentCertUpdated)%)" -ForegroundColor green         Write-Host " With Errors: $($c.WithErrors.ToString("N0"))" -ForegroundColor $(if ($c.WithErrors -gt 0) { "Red" } else { "Green" })         Write-Host " Peak Memory: ${stPeakMemMB} MB" -ForegroundColor Cyan         Write-Host " Ora: $([matematica]::Round($stTotal/60,1)) min" -Primo pianoColore bianco         Write-Host " Dashboard: $htmlPath" -ForegroundColor white         restituire [PSCustomObject]$stats     }     #ENDREGION MODALITÀ STREAMING } else {     Write-Error "Percorso di input non trovato: $InputPath"     uscita 1 }                                                      

Serve aiuto?

Vuoi altre opzioni?

Esplorare i vantaggi dell'abbonamento e i corsi di formazione, scoprire come proteggere il dispositivo e molto altro ancora.