Copie e cole este script de exemplo e modifique conforme necessário para o seu ambiente:
<# . SYNOPSIS Agrega dados JSON de estado de Arranque Seguro de vários dispositivos em relatórios de resumo.
. DESCRIÇÃO Lê os ficheiros JSON de estado de Arranque Seguro recolhidos e gera: - Dashboard HTML com gráficos e filtragem - Resumo por NíveldeConfiança - Análise exclusiva do registo de dispositivos para a estratégia de teste Suporta: - Ficheiros por computador: HOSTNAME_latest.json (recomendado) - Ficheiro JSON único Elimina automaticamente a eliminação de duplicados por HostName, mantendo o CollectionTime mais recente. Por predefinição, apenas inclui dispositivos com confiança "Action Req" ou "High" para se concentrar em registos acionáveis. Utilize -IncludeAllConfidenceLevels para substituir.
. PARAMETER InputPath Caminho para ficheiro(s) JSON: - Pasta: lê todos os ficheiros *_latest.json (ou *.json se não houver ficheiros _latest) - Ficheiro: lê um único ficheiro JSON
. PARAMETER OutputPath Caminho para relatórios gerados (predefinição: .\SecureBootReports)
. EXEMPLO # Agregar a partir da pasta de ficheiros por computador (recomendado) .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" # Leituras: \\contoso\SecureBootLogs$\*_latest.json
. EXEMPLO # Localização de saída personalizada .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -OutputPath "C:\Reports\SecureBoot"
. EXEMPLO # Inclua apenas Req de Ação e Alta confiança (comportamento predefinido) .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" #Excludes: Observation, Paused, Not Supported
. EXEMPLO # Inclua todos os níveis de confiança (filtro de substituição) .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncludeAllConfidenceLevels
. EXEMPLO # Filtro de nível de confiança personalizado .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncludeConfidenceLevels @("Action Req", "High", "Observation")
. EXEMPLO # ESCALA EMPRESARIAL: modo incremental – apenas processar ficheiros alterados (execuções subsequentes rápidas) .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncrementalMode # Primeira execução: carregamento completo ~2 horas para dispositivos 500 K # Execuções subsequentes: Segundos se não houver alterações, minutos para deltas
. EXEMPLO # Ignorar HTML se nada tiver sido alterado (mais rápido para monitorização) .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -IncrementalMode -SkipReportIfUnchanged # Se nenhum ficheiro tiver sido alterado desde a última execução: ~5 segundos
. EXEMPLO # Modo apenas de resumo – ignorar tabelas de dispositivos grandes (1-2 minutos vs. mais de 20 minutos) .\Aggregate-SecureBootData.ps1 -InputPath "\\contoso\SecureBootLogs$" -SummaryOnly # Gera CSVs, mas ignora o dashboard HTML com tabelas de dispositivos completas
. NOTAS Emparelhe com Detect-SecureBootCertUpdateStatus.ps1 para implementação empresarial.Veja GPO-DEPLOYMENT-GUIDE.md para obter o guia de implementação completo. O comportamento predefinido exclui dispositivos de Observação, Em Pausa e Não Suportados para focar os relatórios apenas em registos de dispositivos acionáveis.#>
parâmetro( [Parameter(Mandatory = $true)] [cadeia]$InputPath, [Parameter(Mandatory = $false)] [string]$OutputPath = ".\SecureBootReports", [Parameter(Mandatory = $false)] [string]$ScanHistoryPath = ".\SecureBootReports\ScanHistory.json", [Parameter(Mandatory = $false)] [string]$RolloutStatePath, # Path to RolloutState.json to identify InProgress devices [Parameter(Mandatory = $false)] [string]$RolloutSummaryPath, # Path to SecureBootRolloutSummary.json from Orchestrator (contains projection data) [Parameter(Mandatory = $false)] [string[]]$IncludeConfidenceLevels = @("Action Required", "High Confidence"), # Only include these confidence levels (default: actionable buckets only) [Parameter(Mandatory = $false)] [switch]$IncludeAllConfidenceLevels, # Substituir filtro para incluir todos os níveis de confiança [Parameter(Mandatory = $false)] [switch]$SkipHistoryTracking, [Parameter(Mandatory = $false)] [switch]$IncrementalMode, # Enable delta processing - only load changed files since last run [Parameter(Mandatory = $false)] [string]$CachePath, # Path to cache directory (default: OutputPath\.cache) [Parameter(Mandatory = $false)] [int]$ParallelThreads = 8, # Número de threads paralelos para carregamento de ficheiros (PS7+) [Parameter(Mandatory = $false)] [switch]$ForceFullRefresh, # Force full reload even in incremental mode [Parameter(Mandatory = $false)] [switch]$SkipReportIfUnchanged, # Skip HTML/CSV generation if no files changed (just output stats) [Parameter(Mandatory = $false)] [switch]$SummaryOnly, # Generate summary stats only (no large device tables) - much faster [Parameter(Mandatory = $false)] [switch]$StreamingMode # Modo de eficiência de memória: processar segmentos, escrever CSVs incrementalmente, manter apenas resumos na memória )
# Elevar automaticamente para o PowerShell 7 se disponível (6x mais rápido para conjuntos de dados grandes) if ($PSVersionTable.PSVersion.Major -lt 7) { $pwshPath = Get-Command pwsh -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source se ($pwshPath) { Write-Host "PowerShell $($PSVersionTable.PSVersion) detetado – reiniciar com o PowerShell 7 para processamento mais rápido..." -ForegroundColor Yellow # Recompilar lista de argumentos a partir de parâmetros vinculados $relaunchArgs = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $MyInvocation.MyCommand.Path) foreach ($key em $PSBoundParameters.Keys) { $val = $PSBoundParameters[$key] if ($val -is [switch]) { se ($val. IsPresent) { $relaunchArgs += "-$key" } } elseif ($val -is [array]) { $relaunchArgs += "-$key" $relaunchArgs += ($val -join ',') } senão { $relaunchArgs += "-$key" $relaunchArgs += "$val" } } & $pwshPath @relaunchArgs sair $LASTEXITCODE } }
$ErrorActionPreference = "Continuar" $timestamp = Get-Date -Format "yyyyMMdd-HHmmss" $scanTime = Get-Date -Formatar "aaaa-MM-dd HH:mm:ss" $DownloadUrl = "https://aka.ms/getsecureboot" $DownloadSubPage = "Exemplos de Implementação e Monitorização"
Nota: este script não tem dependências noutros scripts. # Para o conjunto de ferramentas completo, transfira a partir de: $DownloadUrl -> $DownloadSubPage
Configuração do #region Write-Host "=" * 60 -ForegroundColor Cyan Write-Host "Agregação de Dados de Arranque Seguro" -ForegroundColor Cyan Write-Host "=" * 60 -ForegroundColor Cyan
# Criar diretório de saída if (-not (Test-Path $OutputPath)) { New-Item -ItemType Directory -Path $OutputPath -Force | Out-Null }
# Carregar dados - suporta formatos CSV (legado) e JSON (nativo) Write-Host "'nLoading data from: $InputPath" -ForegroundColor Yellow
# Função auxiliar para normalizar o objeto do dispositivo (processar as diferenças de nome do campo) função Normalize-DeviceRecord { parâmetro($device) # Handle Hostname vs HostName (JSON uses Hostname, CSV uses HostName) if ($device. PSObject.Properties['Hostname'] -and -not $device. PSObject.Properties['HostName']) { $device | Add-Member -NotePropertyName 'HostName' -NotePropertyValue $device. Nome do anfitrião -Force } # Handle Confidence vs ConfidenceLevel (JSON utiliza Confidence, CSV uses ConfidenceLevel) # ConfidenceLevel é o nome do campo oficial – mapeie Confiança ao mesmo if ($device. PSObject.Properties['Confidence'] -and -not $device. PSObject.Properties['ConfidenceLevel']) { $device | Add-Member -NotePropertyName 'ConfidenceLevel' -NotePropertyValue $device. Confiança - Força } # Controle o estado da atualização através de Event1808Count OR UEFICA2023Status="Updated" # Isto permite controlar quantos dispositivos em cada registo de confiança foram atualizados $event 1808 = 0 if ($device. PSObject.Properties['Event1808Count']) { $event 1808 = [int]$device. Event1808Count } $uefiCaUpdated = $false if ($device. PSObject.Properties['UEFICA2023Status'] - e $device. UEFICA2023Status -eq "Atualizado") { $uefiCaUpdated = $true } if ($event 1808 -gt 0 -or $uefiCaUpdated) { # Marque como atualizado para a lógica de dashboard/implementação - mas NÃO substitua ConfidenceLevel $device | Add-Member -NotePropertyName 'IsUpdated' -NotePropertyValue $true -Force } senão { $device | Add-Member -NotePropertyName 'IsUpdated' -NotePropertyValue $false -Force # Classificação confidenceLevel: # - "Alta Confiança", "Em Observação...", "Temporariamente em Pausa...", "Não Suportado..." = utilizar tal como está # - Tudo o resto (nulo, vazio, "UpdateType:...", "Desconhecido", "N/A") = enquadra-se na Ação Necessária nos contadores # Não é necessária normalização — o ramo else do contador de transmissão em fluxo processa-o } # Handle OEMManufacturerName vs WMI_Manufacturer (JSON uses OEM*, legacy uses WMI_*) if ($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 if ($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 if ($device. PSObject.Properties['FirmwareVersion'] -and -not $device. PSObject.Properties['BIOSDescription']) { $device | Add-Member -NotePropertyName 'BIOSDescription' -NotePropertyValue $device. FirmwareVersion -Force } devolver $device }
Processamento Incremental do #region/Gestão da Cache # Configurar caminhos de cache if (-not $CachePath) { $CachePath = Join-Path $OutputPath ".cache" } $manifestPath = Join-Path $CachePath "FileManifest.json" $deviceCachePath = Join-Path $CachePath "DeviceCache.json"
# Funções de gestão da cache função Get-FileManifest { parâmetro([string]$Path) if (Test-Path $Path) { experimente { $json = Get-Content $Path -Raw | ConverterFrom-Json # Converta PSObject em hash (compatível com PS5.1 – PS7 tem -AsHashtable) $ht = @{} $json. PSObject.Properties | ForEach-Object { $ht[$_. Nome] = $_. Valor } devolver $ht } captura { devolver @{} } } devolver @{} }
função Save-FileManifest { parâmetro([tabela hash]$Manifest, [cadeia]$Path) $dir = Split-Path $Path -Parent if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } $Manifest | ConvertTo-Json -Profundidade 3 -Comprimir | Set-Content $Path -Force }
função Get-DeviceCache { parâmetro([string]$Path) if (Test-Path $Path) { experimente { $cacheData = Get-Content $Path -Raw | ConverterFrom-Json Write-Host " Cache carregada do dispositivo: dispositivos $($cacheData.Count)" -ForegroundColor DarkGray devolver $cacheData } captura { Write-Host " Cache danificada, irá reconstruir" -Primeiro PlanoColor Amarelo devolver @() } } devolver @() }
função Save-DeviceCache { parâmetro($Devices; [cadeia]$Path) $dir = Split-Path $Path -Parent if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } # Converter em matriz e guardar $deviceArray = @($Devices) $deviceArray | ConvertTo-Json -Profundidade 10 -Comprimir | Set-Content $Path -Force Write-Host " Cache do dispositivo guardada: dispositivos $($deviceArray.Count)" -ForegroundColor DarkGray }
função Get-ChangedFiles { parâmetro( [System.IO.FileInfo[]]$AllFiles, [hashtable]$Manifest ) $changed = [System.Collections.ArrayList]::new() $unchanged = [System.Collections.ArrayList]::new() $newManifest = @{} # Criar pesquisa não sensível a maiúsculas e minúsculas do manifesto (normalizar para minúsculas) $manifestLookup = @{} foreach ($mk em $Manifest.Keys) { $manifestLookup[$mk. ToLowerInvariant()] = $Manifest[$mk] } foreach ($file em $AllFiles) { $key = $file. FullName.ToLowerInvariant() # Normalizar caminho para minúsculas $lwt = $file. LastWriteTimeUtc.ToString("o") $newManifest[$key] = @{ LastWriteTimeUtc = $lwt Tamanho = $file. Comprimento } if ($manifestLookup.ContainsKey($key)) { $cached = $manifestLookup[$key] if ($cached. LastWriteTimeUtc -eq $lwt - e $cached. Tamanho -eq $file. Comprimento) { [void]$unchanged. Adicionar($file) continuar } } [vazio]$changed. Adicionar($file) } devolver @{ Alterado = $changed Inalterado = $unchanged NewManifest = $newManifest } }
# Carregamento de ficheiros paralelos ultra-rápidos com processamento em lotes função Load-FilesParallel { parâmetro( [System.IO.FileInfo[]]$Files, [int]$Threads = 8 )
$totalFiles = $Files. Contagem # Utilize lotes de ~1000 ficheiros cada para um melhor controlo de memória $batchSize = [matemática]::Min(1000, [matemática]::Teto($totalFiles / [matemática]::Máx.(1, $Threads))) $batches = [System.Collections.Generic.List[object]]::new()
para ($i = 0; $i -lt $totalFiles; $i += $batchSize) { $end = [matemática]::Min($i + $batchSize, $totalFiles) $batch = $Files[$i.. ($end-1)] $batches. Adicionar($batch) } Write-Host " ($($batches. Contagem) lotes de ~$batchSize ficheiros cada)" -NoNewline -ForegroundColor DarkGray $flatResults = [System.Collections.Generic.List[object]]::new() # Verifique se o Paralelo do PowerShell 7+ está disponível $canParallel = $PSVersionTable.PSVersion.Major -ge 7 if ($canParallel -and $Threads -gt 1) { # PS7+: Processar lotes em paralelo $results = $batches | ForEach-Object -ThrottleLimit $Threads -Parallel { $batchFiles = $_ $batchResults = [System.Collections.Generic.List[object]]::new() foreach ($file no $batchFiles) { experimente { $content = [System.IO.File]::ReadAllText($file. FullName) | ConverterFrom-Json $batchResults.Add($content) } captura { } } $batchResults.ToArray() } foreach ($batch em $results) { if ($batch) { foreach ($item in $batch) { $flatResults.Add($item) } } } } senão { # PS5.1 contingência: Processamento sequencial (ainda rápido para <ficheiros de 10 K) foreach ($file em $Files) { experimente { $content = [System.IO.File]::ReadAllText($file. FullName) | ConverterFrom-Json $flatResults.Add($content) } captura { } } } return $flatResults.ToArray() } #endregion
$allDevices = @() if (Test-Path $InputPath -PathType Leaf) { # Ficheiro JSON único if ($InputPath -like "*.json") { $jsonContent = Get-Content -Path $InputPath -Raw | ConverterFrom-Json $allDevices = @($jsonContent) | ForEach-Object { Normalize-DeviceRecord $_ } Write-Host "Registos $($allDevices.Count) carregados do ficheiro" } senão { Write-Error "Só é suportado o formato JSON. O ficheiro tem de ter .json extensão". sair 1 } } elseif (Test-Path $InputPath -PathType Container) { # Pasta - apenas JSON $jsonFiles = @(Get-ChildItem -Path $InputPath -Filter "*.json" -Recurse -ErrorAction SilentlyContinue | Where-Object { $_. Name -notmatch "ScanHistory|RolloutState|Plano de Implementação" }) # Preferir *_latest.json ficheiros se existirem (modo por computador) $latestJson = $jsonFiles | Where-Object { $_. Nome - como "*_latest.json" } if ($latestJson.Count -gt 0) { $jsonFiles = $latestJson } $totalFiles = $jsonFiles.Count if ($totalFiles -eq 0) { Write-Error "Não foram encontrados ficheiros JSON em: $InputPath" sair 1 } Write-Host "Ficheiros JSON $totalFiles encontrados" -ForegroundColor Gray # Função auxiliar para corresponder aos níveis de confiança (processa formulários curtos e completos) # Definido antecipadamente para que o StreamingMode e os caminhos normais possam utilizá-lo função Test-ConfidenceLevel { parâmetro([cadeia]$Value, [cadeia]$Match) if ([string]::IsNullOrEmpty($Value)) { return $false } comutador ($Match) { "HighConfidence" { return $Value -eq "High Confidence" } "UnderObservation" { return $Value -like "Under Observation*" } "ActionRequired" { return ($Value -like "*Action Required*" -or $Value -eq "Action Required") } "TemporariamentePaused" { return $Value -like "Temporarily Paused*" } "NotSupported" { return ($Value -like "Not Supported*" -or $Value -eq "Not Supported") } predefinição { return $false } } } #region MODO DE TRANSMISSÃO EM FLUXO – Processamento eficiente da memória para grandes conjuntos de dados # Utilize sempre o StreamingMode para processamento com eficiência de memória e dashboard de estilo novo if (-not $StreamingMode) { Write-Host "Auto-enabling StreamingMode (new-style dashboard)" -ForegroundColor Yellow $StreamingMode = $true if (-not $IncrementalMode) { $IncrementalMode = $true } } # Quando -StreamingMode estiver ativado, processe ficheiros em segmentos mantendo apenas contadores na memória.# Os dados ao nível do dispositivo são escritos em ficheiros JSON por segmento para carregamento a pedido no dashboard.# Utilização da memória: ~1,5 GB, independentemente do tamanho do conjunto de dados (vs. 10-20 GB sem transmissão em fluxo).se ($StreamingMode) { Write-Host "MODO DE TRANSMISSÃO EM FLUXO ativado – processamento com eficiência de memória" – Primeiro PlanoColor Verde $streamSw = [System.Diagnostics.Stopwatch]::StartNew() # VERIFICAÇÃO INCREMENTAL: se não tiver sido alterado nenhum ficheiro desde a última execução, ignore totalmente o processamento if ($IncrementalMode -and -not $ForceFullRefresh) { $stManifestDir = Join-Path $OutputPath ".cache" $stManifestPath = Join-Path $stManifestDir "StreamingManifest.json" if (Test-Path $stManifestPath) { Write-Host "A verificar a existência de alterações desde a última execução de transmissão em fluxo..." -ForegroundColor Cyan $stOldManifest = Get-FileManifest -Path $stManifestPath if ($stOldManifest.Count -gt 0) { $stChanged = $false # Verificação rápida: a mesma contagem de ficheiros? if ($stOldManifest.Count -eq $totalFiles) { # Verifique os 100 ficheiros MAIS RECENTEs (ordenados por LastWriteTime descendente) # Se algum ficheiro tiver sido alterado, terá o carimbo de data/hora mais recente e aparecerá primeiro $sampleSize = [matemática]::Min(100, $totalFiles) $sampleFiles = $jsonFiles | Sort-Object LastWriteTimeUtc -Descending | Select-Object -Primeira $sampleSize foreach ($sf no $sampleFiles) { $sfKey = $sf. FullName.ToLowerInvariant() if (-not $stOldManifest.ContainsKey($sfKey)) { $stChanged = $true quebra } # Compare timestamps - cached may be DateTime or string after JSON roundtrip $cachedLWT = $stOldManifest[$sfKey]. LastWriteTimeUtc $fileDT = $sf. LastWriteTimeUtc experimente { # Se a cache já for DateTime (ConvertFrom-Json auto-converts), utilize diretamente if ($cachedLWT -is [DateTime]) { $cachedDT = $cachedLWT.ToUniversalTime() } senão { $cachedDT = [DateTimeOffset]::P arse("$cachedLWT"). UtcDateTime } if ([math]::Abs(($cachedDT - $fileDT). TotalSeconds) -gt 1) { $stChanged = $true quebra } } captura { $stChanged = $true quebra } } } senão { $stChanged = $true } if (-not $stChanged) { # Verificar se existem ficheiros de saída $stSummaryExists = Get-ChildItem (Join-Path $OutputPath "SecureBoot_Summary_*.csv") -EA SilentlyContinue | Select-Object -Primeiro 1 $stDashExists = Get-ChildItem (Join-Path $OutputPath "SecureBoot_Dashboard_*.html") -EA SilentlyContinue | Select-Object -Primeiro 1 if ($stSummaryExists -and $stDashExists) { Write-Host " Não foram detetadas alterações ($totalFiles ficheiros inalterados) – a ignorar o processamento" -ForegroundColor Green Write-Host " Último dashboard: $($stDashExists.FullName)" -ForegroundColor White $cachedStats = Get-Content $stSummaryExists.FullName | ConverterFrom-Csv Write-Host " Dispositivos: $($cachedStats.TotalDevices) | Atualizado: $($cachedStats.Updated) | Erros: $($cachedStats.WithErrors)" -ForegroundColor Gray Write-Host " Concluído em $([math]::Round($streamSw.Elapsed.TotalSeconds, 1)s (sem necessidade de processamento)" -ForegroundColor Green devolver $cachedStats } } senão { # DELTA PATCH: determinar exatamente que ficheiros foram alterados Write-Host " Alterações detetadas - identificar ficheiros alterados..." -ForegroundColor Amarelo $changedFiles = [System.Collections.ArrayList]::new() $newFiles = [System.Collections.ArrayList]::new() foreach ($jf no $jsonFiles) { $jfKey = $jf. FullName.ToLowerInvariant() if (-not $stOldManifest.ContainsKey($jfKey)) { [void]$newFiles.Add($jf) } senão { $cachedLWT = $stOldManifest[$jfKey]. LastWriteTimeUtc $fileDT = $jf. LastWriteTimeUtc experimente { $cachedDT = se ($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 = [matemática]::Round(($totalChanged/$totalFiles) * 100, 1) Write-Host " Alterado: $($changedFiles.Count) | Novo: $($newFiles.Count) | Total: $totalChanged ($changePct%)" -Primeiro PlanoColor Amarelo if ($totalChanged -gt 0 -and $changePct -lt 10) { # DELTA PATCH MODE: <10% alterado, corrigir dados existentes Write-Host " Modo de patch Delta ($changePct% < 10%) – aplicação de patches $totalChanged ficheiros..." -ForegroundColor Green $dataDir = Join-Path $OutputPath "dados" # Carregamento alterado/novos registos de dispositivos $deltaDevices = @{} $allDeltaFiles = @($changedFiles) + @($newFiles) foreach ($df no $allDeltaFiles) { experimente { $devData = Get-Content $df. FullName -Raw | ConverterFrom-Json $dev = Normalize-DeviceRecord $devData if ($dev. HostName) { $deltaDevices[$dev. HostName] = $dev } } captura { } } Write-Host " Carregado $($deltaDevices.Count) registos do dispositivo alterados" -ForegroundColor Gray # Para cada categoria JSON: remover entradas antigas para nomes de anfitrião alterados, adicionar novas entradas $categoryFiles = @("erros", "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 em $deltaDevices.Keys) { [void]$changedHostnames.Add($hn) } foreach ($cat no $categoryFiles) { $catPath = Join-Path $dataDir "$cat.json" if (Test-Path $catPath) { experimente { $catData = Get-Content $catPath -Raw | ConverterFrom-Json # Remover entradas antigas para nomes de anfitrião alterados $catData = @($catData | Where-Object { -not $changedHostnames.Contains($_. HostName) }) # Reclassifique cada dispositivo alterado em categorias # (será adicionado abaixo após a classificação) $catData | ConvertTo-Json -Profundidade 5 | Set-Content $catPath -Encoding UTF8 } captura { } } } # Classifique cada dispositivo alterado e acrescente aos ficheiros de categoria corretos foreach ($dev em $deltaDevices.Values) { $slim = [encomendado]@{ HostName = $dev. HostName WMI_Manufacturer = se ($dev. PSObject.Properties['WMI_Manufacturer']) { $dev. WMI_Manufacturer } senão { "" } WMI_Model = se ($dev. PSObject.Properties['WMI_Model']) { $dev. WMI_Model } senão { "" } BucketId = se ($dev. PSObject.Properties['BucketId']) { $dev. BucketId } senão { "" } ConfidenceLevel = se ($dev. PSObject.Properties['ConfidenceLevel']) { $dev. ConfidenceLevel } senão { "" } IsUpdated = $dev. IsUpdated UEFICA2023Error = se ($dev. PSObject.Properties['UEFICA2023Error']) { $dev. UEFICA2023Error } senão { $null } SecureBootTaskStatus = se ($dev. PSObject.Properties['SecureBootTaskStatus']) { $dev. SecureBootTaskStatus } else { "" } KnownIssueId = se ($dev. PSObject.Properties['KnownIssueId']) { $dev. KnownIssueId } senão { $null } SkipReasonKnownIssue = se ($dev. PSObject.Properties['SkipReasonKnownIssue']) { $dev. SkipReasonKnownIssue } else { $null } } $isUpd = $dev. IsUpdated -eq $true $conf = se ($dev. PSObject.Properties['ConfidenceLevel']) { $dev. ConfidenceLevel } senão { "" } $hasErr = (-não [cadeia]::IsNullOrEmpty($dev. UEFICA2023Error) - e $dev. UEFICA2023Error -ne "0" - e $dev. UEFICA2023Error -ne "") $tskDis = ($dev. SecureBootTaskEnabled -eq $false -ou $dev. SecureBootTaskStatus -eq 'Disabled' -or $dev. SecureBootTaskStatus -eq "NotFound") $tskNF = ($dev. SecureBootTaskStatus -eq "NotFound") $sbOn = ($dev. SecureBootEnabled -ne $false - e "$($dev. SecureBootEnabled)" -ne "False") $e 1801 = se ($dev. PSObject.Properties['Event1801Count']) { [int]$dev. Event1801Count } senão { 0 } $e 1808 = se ($dev. PSObject.Properties['Event1808Count']) { [int]$dev. Event1808Count } else { 0 } $e 1803 = se ($dev. PSObject.Properties['Event1803Count']) { [int]$dev. Evento1803Count } senão { 0 } $mKEK = ($e 1803 -gt 0 -ou $dev. MissingKEK -eq $true) $hKI = ((-não [cadeia]::IsNullOrEmpty($dev. SkipReasonKnownIssue)) -ou (-not [string]::IsNullOrEmpty($dev. KnownIssueId))) $rStat = se ($dev. PSObject.Properties['RolloutStatus']) { $dev. RolloutStatus } else { "" } # Acrescentar a ficheiros de categoria correspondentes $targets = @() if ($isUpd) { $targets += "updated_devices" } if ($hasErr) { $targets += "errors" } if ($hKI) { $targets += "known_issues" } if ($mKEK) { $targets += "missing_kek" } if (-not $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') -ou ($tskNF -and $hasErr))) { $targets += "perm_failures" } if (-not $isUpd -and (Test-ConfidenceLevel $conf 'ActionRequired')) { $targets += "action_required" } if (-not $sbOn) { $targets += "secureboot_off" } if ($e 1801 -gt 0 -and $e 1808 -eq 0 -and -not $hasErr -and $rStat -eq "InProgress") { $targets += "rollout_inprogress" } foreach ($tgt em $targets) { $tgtPath = Join-Path $dataDir "$tgt.json" if (Test-Path $tgtPath) { $existing = Get-Content $tgtPath -Raw | ConverterFrom-Json $existing = @($existing) + @([PSCustomObject]$slim) $existing | ConvertTo-Json -Profundidade 5 | Set-Content $tgtPath -Encoding UTF8 } } } # Regenerar CSVs de JSONs corrigidos Write-Host " Regenerar CSVs a partir de dados corrigidos..." -ForegroundColor Gray $newTimestamp = Get-Date -Format "yyyyMMdd-HHmmss" foreach ($cat no $categoryFiles) { $catJsonPath = Join-Path $dataDir "$cat.json" $catCsvPath = Join-Path $OutputPath "SecureBoot_${cat}_$newTimestamp.csv" if (Test-Path $catJsonPath) { experimente { $catJsonData = Get-Content $catJsonPath -Raw | ConverterFrom-Json if ($catJsonData.Count -gt 0) { $catJsonData | Export-Csv -Path $catCsvPath -NoTypeInformation -Encoding UTF8 } } captura { } } } # Recount stats from the patched JSON files (Estatísticas de recontagem dos ficheiros JSON corrigidos) Write-Host " Recálculo resumo dos dados corrigidos..." -ForegroundColor Gray $patchedStats = [encomendado]@{ 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 no $categoryFiles) { $catPath = Join-Path $dataDir "$cat.json" $cnt = 0 if (Test-Path $catPath) { try { $cnt = (Get-Content $catPath -Raw | ConvertFrom-Json). Count } catch { } } switch ($cat) { "updated_devices" { $pUpdated = $cnt } "erros" { $pErrors = $cnt } "known_issues" { $pKI = $cnt } "missing_kek" { $pKEK = $cnt } "not_updated" { } # computed "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). Contagem $pTotal = $pUpdated + $pNotUpdated + $pSBOff Write-Host " Patch delta concluído: $totalChanged dispositivos atualizados" -ForegroundColor Green Write-Host " Total: $pTotal | Atualizado: $pUpdated | Não Desatualizado: $pNotUpdated | Erros: $pErrors" -ForegroundColor White # Atualizar manifesto $stManifestDir = Join-Path $OutputPath ".cache" $stNewManifest = @{} foreach ($jf no $jsonFiles) { $stNewManifest[$jf. FullName.ToLowerInvariant()] = @{ LastWriteTimeUtc = $jf. LastWriteTimeUtc.ToString("o"); Tamanho = $jf. Comprimento } } Save-FileManifest -Manifest $stNewManifest -Path $stManifestPath Write-Host " Concluído em $([math]::Round($streamSw.Elapsed.TotalSeconds, 1)s (patch delta - $totalChanged dispositivos)" -ForegroundColor Green # Fall through to full streaming reprocess to regenerate HTML dashboard # Os ficheiros de dados já foram corrigidos, pelo que garante que o dashboard se mantém atualizado Write-Host " Regenerar dashboard a partir de dados corrigidos..." -Primeiro PlanoColor Amarelo } senão { Write-Host " $changePct% ficheiros alterados (>= 10%) - reprocessamento de transmissão em fluxo completo necessário" -ForegroundColor Amarelo } } } } } # Criar subdiretório de dados para ficheiros JSON de dispositivos a pedido $dataDir = Join-Path $OutputPath "dados" if (-not (Test-Path $dataDir)) { New-Item -ItemType Directory -Path $dataDir -Force | Out-Null } # Eliminação de duplicados através de HashSet (O(1) por pesquisa, ~50 MB para nomes de anfitrião de 600 mil) $seenHostnames = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) # Contadores de resumo simples (substitui $allDevices + $uniqueDevices na memória) $c = @{ Total = 0; SBEnabled = 0; SBOff = 0 Atualizado = 0; HighConf = 0; UnderObs = 0; ActionReq = 0; TempPaused = 0; Não Suportado = 0; NoConfData = 0 TaskDisabled = 0; TaskNotFound = 0; TaskDisabledNotUpdated = 0 WithErrors = 0; Entrada = 0; NotYetInitiated = 0; RolloutInProgress = 0 WithKnownIssues = 0; WithMissingKEK = 0; TempFailures = 0; PermFailures = 0; NeedsReboot = 0 Atualização Pendente = 0 } # Registo de registos para AtRisk/SafeList (conjuntos leves) $stFailedBuckets = [System.Collections.Generic.HashSet[string]]::new() $stSuccessBuckets = [System.Collections.Generic.HashSet[string]]::new() $stAllBuckets = @{} $stMfrCounts = @{} $stErrorCodeCounts = @{}; $stErrorCodeSamples = @{} $stKnownIssueCounts = @{} # Ficheiros de dados do dispositivo no modo batch: acumular por segmento, remover os limites dos segmentos $stDeviceFiles = @("erros", "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 no $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 (only essential fields, ~200 bytes vs~2KB full) função Get-SlimDevice { parâmetro($Dev) devolver [encomendado]@{ HostName = $Dev.HostName WMI_Manufacturer = se ($Dev.PSObject.Properties['WMI_Manufacturer']) { $Dev.WMI_Manufacturer } else { "" } WMI_Model = se ($Dev.PSObject.Properties['WMI_Model']) { $Dev.WMI_Model } else { "" } BucketId = se ($Dev.PSObject.Properties['BucketId']) { $Dev.BucketId } else { "" } ConfidenceLevel = se ($Dev.PSObject.Properties['ConfidenceLevel']) { $Dev.ConfidenceLevel } else { "" } IsUpdated = $Dev.IsUpdated UEFICA2023Error = if ($Dev.PSObject.Properties['UEFICA2023Error']) { $Dev.UEFICA2023Error } else { $null } SecureBootTaskStatus = se ($Dev.PSObject.Properties['SecureBootTaskStatus']) { $Dev.SecureBootTaskStatus } else { "" } KnownIssueId = se ($Dev.PSObject.Properties['KnownIssueId']) { $Dev.KnownIssueId } else { $null } SkipReasonKnownIssue = se ($Dev.PSObject.Properties['SkipReasonKnownIssue']) { $Dev.SkipReasonKnownIssue } else { $null } UEFICA2023Status = se ($Dev.PSObject.Properties['UEFICA2023Status']) { $Dev.UEFICA2023Status } else { $null } AvailableUpdatesPolicy = se ($Dev.PSObject.Properties['AvailableUpdatesPolicy']) { $Dev.AvailableUpdatesPolicy } else { $null } WinCSKeyApplied = se ($Dev.PSObject.Properties['WinCSKeyApplied']) { $Dev.WinCSKeyApplied } else { $null } } } # Descarregue batch para o ficheiro JSON (modo de acréscimo) função Flush-DeviceBatch { parâmetro([string]$StreamName, [System.Collections.Generic.List[object]]$Batch) if ($Batch.Count -eq 0) { return } $fPath = $stDeviceFilePaths[$StreamName] $fSb = [System.Text.StringBuilder]::new() foreach ($fDev no $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 DE TRANSMISSÃO EM FLUXO PRINCIPAL $stChunkSize = se ($totalFiles -le 10000) { $totalFiles } senão { 10000 } $stTotalChunks = [matemática]::Teto($totalFiles/$stChunkSize) $stPeakMemMB = 0 se ($stTotalChunks -gt 1) { Write-Host "Processing $totalFiles files in $stTotalChunks chunks of $stChunkSize (streaming, $ParallelThreads threads):" -ForegroundColor Cyan } senão { Write-Host "Processing $totalFiles files (streaming, $ParallelThreads threads):" -ForegroundColor Cyan } para ($ci = 0; $ci -lt $stTotalChunks; $ci++) { $cStart = $ci * $stChunkSize $cEnd = [matemática]::Min($cStart + $stChunkSize, $totalFiles) - 1 $cFiles = $jsonFiles[$cStart.. $cEnd] se ($stTotalChunks -gt 1) { Write-Host " Segmento $($ci + 1)/$stTotalChunks (ficheiros $($cFiles.Count): " -NoNewline -ForegroundColor Gray } senão { Write-Host " A carregar ficheiros $($cFiles.Count): " -NoNewline -ForegroundColor Gray } $cSw = [System.Diagnostics.Stopwatch]::StartNew() $rawDevices = Load-FilesParallel -Files $cFiles -Threads $ParallelThreads # Listas de lote por segmento $cBatches = @{} foreach ($df no $stDeviceFiles) { $cBatches[$df] = [System.Collections.Generic.List[object]::new() } $cNew = 0; $cDupe = 0 foreach ($raw no $rawDevices) { if (-not $raw) { continue } $device = Normalize-DeviceRecord $raw $hostname = $device. HostName if (-not $hostname) { continue } if ($seenHostnames.Contains($hostname)) { $cDupe++; continue } [void]$seenHostnames.Add($hostname) $cNew++; $c.Total++ $sbOn = ($device. SecureBootEnabled -ne $false - e "$($device. SecureBootEnabled)" -ne "False") se ($sbOn) { $c.SBEnabled++ } senão { $c.SBOff++; $cBatches["secureboot_off"]. Add((Get-SlimDevice $device)) } $isUpd = $device. IsUpdated -eq $true $conf = se ($device. PSObject.Properties['ConfidenceLevel'] - e $device. ConfidenceLevel) { "$($device. ConfidenceLevel)" } senão { "" } $hasErr = (-não [cadeia]::IsNullOrEmpty($device. UEFICA2023Error) -e "$($device. UEFICA2023Error)" -ne "0" -e "$($device. UEFICA2023Error)" -ne "") $tskDis = ($device. SecureBootTaskEnabled -eq $false -ou "$($device. SecureBootTaskStatus)" -eq "Disabled" ou "$($device. SecureBootTaskStatus)" -eq "NotFound") $tskNF = ("$($device. SecureBootTaskStatus)" -eq "NotFound") $bid = se ($device. PSObject.Properties['BucketId'] - e $device. BucketId) { "$($device. BucketId)" } senão { "" } $e 1808 = se ($device. PSObject.Properties['Event1808Count']) { [int]$device. Event1808Count } else { 0 } $e 1801 = se ($device. PSObject.Properties['Event1801Count']) { [int]$device. Event1801Count } senão { 0 } $e 1803 = se ($device. PSObject.Properties['Event1803Count']) { [int]$device. Evento1803Count } senão { 0 } $mKEK = ($e 1803 -gt 0 -ou $device. MissingKEK -eq $true -ou "$($device. MissingKEK)" -eq "True") $hKI = ((-não [cadeia]::IsNullOrEmpty($device. SkipReasonKnownIssue)) -ou (-not [string]::IsNullOrEmpty($device. KnownIssueId))) $rStat = se ($device. PSObject.Properties['RolloutStatus']) { $device. RolloutStatus } else { "" } $mfr = se ($device. PSObject.Properties['WMI_Manufacturer'] -and -not [string]::IsNullOrEmpty($device. WMI_Manufacturer)) { $device. WMI_Manufacturer } senão { "Desconhecido" } $bid = se (-não [cadeia]::IsNullOrEmpty($bid)) { $bid } senão { "" } # Pré-computação Atualização Pendente sinalizador (política/WinCS aplicado, estado ainda não Atualizado, SB ATIVADO, tarefa não desativada) $uefiStatus = se ($device. PSObject.Properties['UEFICA2023Status']) { "$($device. UEFICA2023Status)" } else { "" } $hasPolicy = ($device. PSObject.Properties['AvailableUpdatesPolicy'] -and $null -ne $device. AvailableUpdatesPolicy e "$($device. AvailableUpdatesPolicy)" -ne '') $hasWinCS = ($device. PSObject.Properties['WinCSKeyApplied'] - e $device. WinCSKeyApplied -eq $true) $statusPending = ([string]::IsNullOrEmpty($uefiStatus) -or $uefiStatus -eq 'NotStarted' -or $uefiStatus -eq 'InProgress') $isUpdatePending = (($hasPolicy -ou $hasWinCS) - e $statusPending -e -not $isUpd -and $sbOn -and -not $tskDis) se ($isUpd) { $c.Updated++; [void]$stSuccessBuckets.Add($bid); $cBatches["updated_devices"]. Add((Get-SlimDevice $device)) # Controle os dispositivos atualizados que precisam de ser reiniciados (UEFICA2023Status=Atualizado, mas Evento1808=0) se ($e 1808 -eq 0) { $c.NeedsReboot++; $cBatches["needs_reboot"]. Add((Get-SlimDevice $device)) } } elseif (-não $sbOn) { # SecureBoot OFF — fora do âmbito, não classifique por confiança } 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++ } } se ($tskDis) { $c.TaskDisabled++; $cBatches["task_disabled"]. Add((Get-SlimDevice $device)) } if ($tskNF) { $c.TaskNotFound++ } if (-not $isUpd -and $tskDis) { $c.TaskDisabledNotUpdated++ } se ($hasErr) { $c.WithErrors++; [void]$stFailedBuckets.Add($bid); $cBatches["erros"]. Add((Get-SlimDevice $device)) $ec = $device. UEFICA2023Error if (-not $stErrorCodeCounts.ContainsKey($ec)) { $stErrorCodeCounts[$ec] = 0; $stErrorCodeSamples[$ec] = @() } $stErrorCodeCounts[$ec]++ if ($stErrorCodeSamples[$ec]. Contagem -lt 5) { $stErrorCodeSamples[$ec] += $hostname } } se ($hKI) { $c.WithKnownIssues++; $cBatches["known_issues"]. Add((Get-SlimDevice $device)) $ki = se (-não [cadeia]::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 "InProgress") { $c.RolloutInProgress++; $cBatches["rollout_inprogress"]. Add((Get-SlimDevice $device)) } if ($e 1801 -gt 0 -and $e 1808 -eq 0 -and -not $hasErr -and $rStat -ne "InProgress") { $c.NotYetInitiated++ } if ($rStat -eq "InProgress" -and $e 1808 -eq 0) { $c.InProgress++ } # Atualização Pendente: política ou WinCS aplicada, estado pendente, SB ATIVADO, tarefa não desativada se ($isUpdatePending) { $c.UpdatePending++; $cBatches["update_pending"]. Add((Get-SlimDevice $device)) } if (-not $isUpd -and $sbOn) { $cBatches["not_updated"]. Add((Get-SlimDevice $device)) } # Em Dispositivos de observação (separados da Ação Necessária) if (-not $isUpd -and (Test-ConfidenceLevel $conf 'UnderObservation')) { $cBatches["under_observation"]. Add((Get-SlimDevice $device)) } # Ação Necessária: não atualizado, SB ATIVADO, não correspondendo a outras categorias de confiança, não Atualização Pendente 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; Atualizado=0; UpdatePending=0; HighConf=0; UnderObs=0; ActionReq=0; TempPaused=0; NotSupported=0; SBOff=0; WithErrors=0 } } $stMfrCounts[$mfr]. Total++ se ($isUpd) { $stMfrCounts[$mfr]. Atualizado++ } 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++ } # Controlar todos os dispositivos por registo (incluindo BucketId vazio) $bucketKey = se ($bid -and $bid -ne "") { $bid } else { "(empty)" } if (-not $stAllBuckets.ContainsKey($bucketKey)) { $stAllBuckets[$bucketKey] = @{ Count=0; Atualizado=0; Manufacturer=$mfr; Model=""; BIOS="" } if ($device. PSObject.Properties['WMI_Model']) { $stAllBuckets[$bucketKey]. Modelo = $device. WMI_Model } if ($device. PSObject.Properties['BIOSDescription']) { $stAllBuckets[$bucketKey]. BIOS = $device. BIOSDescription } } $stAllBuckets[$bucketKey]. Contar++ se ($isUpd) { $stAllBuckets[$bucketKey]. Atualizado++ } } # Descarregue lotes para o disco foreach ($df no $stDeviceFiles) { Flush-DeviceBatch -StreamName $df -Batch $cBatches[$df] } $rawDevices = $null; $cBatches = $null; [System.GC]::Collect() $cSw.Stop() $cTime = [Matemática]::Round($cSw.Elapsed.TotalSeconds, 1) $cRem = $stTotalChunks - $ci - 1 $cEta = se ($cRem -gt 0) { " | ETA: ~$([Matemática]::Round($cRem * $cSw.Elapsed.TotalSeconds / 60, 1)) min" } else { "" } $cMem = [matemática]::Round([System.GC]::GetTotalMemory($false) / 1MB, 0) if ($cMem -gt $stPeakMemMB) { $stPeakMemMB = $cMem } Write-Host " + $cNew novo, $cDupe dupes, ${cTime}s | Mem: ${cMem}MB$cEta" -ForegroundColor Green } # Finalizar matrizes JSON foreach ($dfName no $stDeviceFiles) { [System.IO.File]::AppendAllText($stDeviceFilePaths[$dfName], "'n]", [System.Text.Encoding]::UTF8) Write-Host " $dfName.json: $($stDeviceFileCounts[$dfName]) devices" -ForegroundColor DarkGray } # Estatísticas derivadas da computação $stAtRisk = 0; $stSafeList = 0 foreach ($bid em $stAllBuckets.Keys) { $b = $stAllBuckets[$bid]; $nu = $b.Count - $b.Updated if ($stFailedBuckets.Contains($bid)) { $stAtRisk += $nu } elseif ($stSuccessBuckets.Contains($bid)) { $stSafeList += $nu } } $stAtRisk = [matemática]::Max(0, $stAtRisk - $c.WithErrors) # NotUptodate = count from not_updated batch (devices with SB ON and not updated) $stNotUptodate = $stDeviceFileCounts["not_updated"] $stats = [encomendado]@{ ReportGeneratedAt = (Get-Date). ToString("aaaa-MM-dd HH:mm:ss") TotalDevices = $c.Total; SecureBootEnabled = $c.SBEnabled; SecureBootOFF = $c.SBOff Atualizado = $c.Updated; HighConfidence = $c.HighConf; UnderObservation = $c.UnderObs ActionRequired = $c.ActionReq; TemporariamentePaused = $c.TempPaused; NotSupported = $c.NotSupported NoConfidenceData = $c.NoConfData; TaskDisabled = $c.TaskDisabled; TaskNotFound = $c.TaskNotFound TaskDisabledNotUpdated = $c.TaskDisabledNotUpdated CertificatesUpdated = $c.Updated; NotUptodate = $stNotUptodate; Totalmente Atualizado = $c.Updated UpdatesPending = $stNotUptodate; UpdatesComplete = $c.Updated WithErrors = $c.WithErrors; InProgress = $c.InProgress; NotYetInitiated = $c.NotYetInitiated RolloutInProgress = $c.RolloutInProgress; WithKnownIssues = $c.WithKnownIssues WithMissingKEK = $c.WithMissingKEK; TemporaryFailures = $c.TempFailures; PermanentFailures = $c.PermFailures NeedsReboot = $c.NeedsReboot; UpdatePending = $c.UpdatePending AtRiskDevices = $stAtRisk; SafeListDevices = $stSafeList PercentWithErrors = se ($c.Total -gt 0) { [matemática]::Round(($c.WithErrors/$c.Total)*100,2) } senão { 0 } PercentAtRisk = se ($c.Total -gt 0) { [matemática]::Round(($stAtRisk/$c.Total)*100,2) } senão { 0 } PercentSafeList = se ($c.Total -gt 0) { [matemática]::Round(($stSafeList/$c.Total)*100,2) } senão { 0 } PercentHighConfidence = se ($c.Total -gt 0) { [matemática]::Round(($c.HighConf/$c.Total)*100,1) } senão { 0 } PercentCertUpdated = se ($c.Total -gt 0) { [matemática]::Round(($c.Updated/$c.Total)*100,1) } senão { 0 } PercentActionRequired = se ($c.Total -gt 0) { [matemática]::Round(($c.ActionReq/$c.Total)*100,1) } senão { 0 } PercentNotUptodate = se ($c.Total -gt 0) { [matemática]::Round($stNotUptodate/$c.Total*100,1) } senão { 0 } PercentFullyUpdated = se ($c.Total -gt 0) { [matemática]::Round(($c.Updated/$c.Total)*100,1) } senão { 0 } UniqueBuckets = $stAllBuckets.Count; PeakMemoryMB = $stPeakMemMB; ProcessingMode = "Streaming" } # Escrever CSVs [PSCustomObject]$stats | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_Summary_$timestamp.csv") -NoTypeInformation -Encoding UTF8 $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Descending | ForEach-Object { [PSCustomObject]@{ Manufacturer=$_. Chave; Count=$_. Value.Total; Atualizado=$_. Value.Updated; HighConfidence=$_. Value.HighConf; ActionRequired=$_. Value.ActionReq } } | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_ByManufacturer_$timestamp.csv") -NoTypeInformation -Encoding UTF8 $stErrorCodeCounts.GetEnumerator() | Sort-Object Valor -Descendente | ForEach-Object { [PSCustomObject]@{ ErrorCode=$_. Chave; Count=$_. Valor; SampleDevices=($stErrorCodeSamples[$_. Chave] -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=$_. Chave; Count=$_. Value.Count; Atualizado=$_. Value.Updated; NotUpdated=$_. Value.Count-$_. Value.Updated; Manufacturer=$_. Value.Manufacturer } } | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_UniqueBuckets_$timestamp.csv") -NoTypeInformation -Encoding UTF8 # Gerar CSVs compatíveis com o orchestrator (nomes de ficheiro esperados para Start-SecureBootRolloutOrchestrator.ps1) $notUpdatedJsonPath = Join-Path $dataDir "not_updated.json" if (Test-Path $notUpdatedJsonPath) { experimente { $nuData = Get-Content $notUpdatedJsonPath -Raw | ConverterFrom-Json if ($nuData.Count -gt 0) { # NotUptodate CSV - o orquestrador procura *NotUptodate*.csv $nuData | Export-Csv -Path (Join-Path $OutputPath "SecureBoot_NotUptodate_$timestamp.csv") -NoTypeInformation -Encoding UTF8 Write-Host " Orchestrator CSV: SecureBoot_NotUptodate_$timestamp.csv ($($nuData.Count)" -ForegroundColor Gray } } captura { } } # Escreva dados JSON para o dashboard $stats | ConvertTo-Json -Profundidade 3 | Set-Content (Join-Path $dataDir "summary.json") -Encoding UTF8 # CONTROLO HISTÓRICO: Guardar o ponto de dados para o gráfico de tendências # Utilize uma localização de cache estável para que os dados de tendência persistam entre pastas de agregação com carimbo de data/hora. # Se OutputPath for semelhante a "...\Aggregation_yyyyMMdd_HHmmss", a cache será colocada na pasta principal.Caso contrário, a cache entra no próprio OutputPath.$parentDir = Split-Path $OutputPath -Parent $leafName = Split-Path $OutputPath -Leaf if ($leafName -match '^Aggregation_\d{8}' -or $leafName -eq 'Aggregation_Current') { # Pasta com carimbo de data/hora criada pelo Orchestrator — utilize o elemento principal para a cache estável $historyPath = Join-Path $parentDir ".cache\trend_history.json" } senão { $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) { experimente { $historyData = @(Get-Content $historyPath -Raw | ConvertFrom-Json) } catch { $historyData = @() } } # Verifique também dentro de OutputPath\.cache\ (localização legada de versões mais antigas) # Intercalar quaisquer pontos de dados que ainda não estejam no histórico primário if ($leafName -eq 'Aggregation_Current' -or $leafName -match '^Aggregation_\d{8}') { $innerHistoryPath = Join-Path $OutputPath ".cache\trend_history.json" if ((Test-Path $innerHistoryPath) -and $innerHistoryPath -ne $historyPath) { experimente { $innerData = @(Get-Content $innerHistoryPath -Raw | ConvertFrom-Json) $existingDates = @($historyData | ForEach-Object { $_. Data }) foreach ($entry no $innerData) { if ($entry. Data e $entry. Date -notin $existingDates) { $historyData += $entry } } if ($innerData.Count -gt 0) { Write-Host " Pontos de dados $($innerData.Count) intercalados da cache interna" -ForegroundColor DarkGray } } captura { } } }
# BOOTSTRAP: se o histórico de tendências estiver vazio/disperso, reconstrua a partir de dados históricos 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 = @{} # Origem 1: CSVs de Resumo dentro da pasta atual (Aggregation_Current mantém todos os CSVs de Resumo) $localSummaries = Get-ChildItem $OutputPath -Filter "SecureBoot_Summary_*.csv" -EA SilentlyContinue | Nome do Sort-Object foreach ($summCsv no $localSummaries) { experimente { $summ = Import-Csv $summCsv.FullName | Select-Object -Primeiro 1 if ($summ. TotalDevices - e [int]$summ. TotalDevices -gt 0 -e $summ. ReportGeneratedAt) { $dateStr = ([datetime]$summ. ReportGeneratedAt). ToString("aaaa-MM-dd") $updated = se ($summ. Atualizado) { [int]$summ. Atualizado } senão { 0 } $notUpd = se ($summ. NotUptodate) { [int]$summ. NotUptodate } else { [int]$summ. TotalDevices - $updated } $dailyData[$dateStr] = [PSCustomObject]@{ Data = $dateStr; Total = [int]$summ. TotalDevices; Atualizado = $updated; Não Desatualizado = $notUpd NeedsReboot = 0; Erros = 0; ActionRequired = se ($summ. ActionRequired) { [int]$summ. ActionRequired } senão { 0 } } } } captura { } } # Origem 2: pastas antigas com carimbo de data/hora Aggregation_* (legadas, se ainda existirem) $aggFolders = Get-ChildItem $parentDir -Directory -Filter "Aggregation_*" -EA SilentlyContinue | Where-Object { $_. Name -match '^Aggregation_\d{8}' } | Nome do Sort-Object foreach ($folder em $aggFolders) { $summCsv = Get-ChildItem $folder. FullName -Filter "SecureBoot_Summary_*.csv" -EA SilentlyContinue | Select-Object -Primeiro 1 se ($summCsv) { experimente { $summ = Import-Csv $summCsv.FullName | Select-Object -Primeiro 1 if ($summ. TotalDevices - e [int]$summ. TotalDevices -gt 0) { $dateStr = $folder. Nome - substitua '^Aggregation_(\d{4})(\d{2})(\d{2})_.*', '$1-$2-$3' $updated = se ($summ. Atualizado) { [int]$summ. Atualizado } senão { 0 } $notUpd = se ($summ. NotUptodate) { [int]$summ. NotUptodate } else { [int]$summ. TotalDevices - $updated } $dailyData[$dateStr] = [PSCustomObject]@{ Data = $dateStr; Total = [int]$summ. TotalDevices; Atualizado = $updated; Não Desatualizado = $notUpd NeedsReboot = 0; Erros = 0; ActionRequired = se ($summ. ActionRequired) { [int]$summ. ActionRequired } senão { 0 } } } } captura { } } } # Origem 3: RolloutState.json WaveHistory (tem carimbos de data/hora por onda do dia 1) # Isto fornece pontos de dados de linha de base mesmo quando não existem pastas de agregação antigas $rolloutStatePaths = @( (Join-Path $parentDir "RolloutState\RolloutState.json"), (Join-Path $OutputPath "RolloutState\RolloutState.json") ) foreach ($rsPath no $rolloutStatePaths) { if (Test-Path $rsPath) { experimente { $rsData = Get-Content $rsPath -Raw | ConverterFrom-Json if ($rsData.WaveHistory) { # Utilizar datas de início de onda como pontos de dados de tendência # Calcular dispositivos cumulativos direcionados para cada onda $cumulativeTargeted = 0 foreach ($wave em $rsData.WaveHistory) { se ($wave. StartedAt -and $wave. DeviceCount) { $waveDate = ([datetime]$wave. StartedAt). ToString("aaaa-MM-dd") $cumulativeTargeted += [int]$wave. DeviceCount if (-not $dailyData.ContainsKey($waveDate)) { # Aproximado: na hora de início da onda, apenas os dispositivos de ondas anteriores foram atualizados $dailyData[$waveDate] = [PSCustomObject]@{ Data = $waveDate; Total = $c.Total; Atualizado = [math]::Max(0, $cumulativeTargeted - [int]$wave. DeviceCount) NotUpdated = $c.Total - [math]::Max(0, $cumulativeTargeted - [int]$wave. DeviceCount) NeedsReboot = 0; Erros = 0; ActionRequired = 0 } } } } } } captura { } break # Use first found } }
if ($dailyData.Count -gt 0) { $historyData = @($dailyData.GetEnumerator() | Sort-Object Chave | ForEach-Object { $_. Valor }) Write-Host " Bootstrapped $($historyData.Count) data points from historical summaries" -ForegroundColor Green } }
# Adicione o ponto de dados atual (eliminação de duplicados por dia - mantenha o mais recente por dia) $todayKey = (Data de Obtenção). ToString("aaaa-MM-dd") $existingToday = $historyData | Where-Object { "$($_. Date)" -like "$todayKey*" } se ($existingToday) { # Substitua a entrada de hoje $historyData = @($historyData | Where-Object { "$($_. Date)" -notlike "$todayKey*" }) } $historyData += [PSCustomObject]@{ Data = $todayKey Total = $c.Total Atualizado = $c.Updated Não Desatualizado = $stNotUptodate NeedsReboot = $c.NeedsReboot Erros = $c.WithErrors ActionRequired = $c.ActionReq } # Remova os pontos de dados incorretos (0 no total) e mantenha os últimos 90 $historyData = @($historyData | Where-Object { [int]$_. Total -gt 0 }) # Sem limite — os dados de tendência são ~100 bytes/entry, um ano completo = ~36 KB $historyData | ConvertTo-Json -Profundidade 3 | Set-Content $historyPath -Encoding UTF8 Write-Host " Histórico de tendências: $($historyData.Count) pontos de dados" -ForegroundColor DarkGray # Criar dados do gráfico de tendências para HTML $trendLabels = ($historyData | ForEach-Object { "'$($_. Date)'" }) -join "," $trendUpdated = ($historyData | ForEach-Object { $_. Atualizado }) -join "," $trendNotUpdated = ($historyData | ForEach-Object { $_. NotUpdated }) -join "," $trendTotal = ($historyData | ForEach-Object { $_. Total }) -join "," # Projeção: expandir linha de tendência utilizando duplicação exponencial (2,4,8,16...) # Deriva o tamanho das ondas e o período de observação dos dados reais do histórico de tendências.# - Tamanho da onda = o maior aumento de período único observado na história (a onda mais recente implementada) # - Dias de observação = dias de calendário médios entre pontos de dados de tendência (com que frequência executamos) # Em seguida, duplica o tamanho da onda em cada período, correspondendo à estratégia de crescimento 2x do orquestrador.$projLabels = ""; $projUpdated = ""; $projNotUpdated = ""; $hasProjection = $false if ($historyData.Count -ge 2) { $lastUpdated = $c.Updated $remaining = $stNotUptodate # Apenas dispositivos SB-ON não atualizados (exclui SecureBoot OFF) $projDates = @(); $projValues = @(); $projNotUpdValues = @() $projDate = Get-Date
# Derivar o tamanho das ondas e o período de observação do histórico de tendências $increments = @() $dayGaps = @() para ($hi = 1; $hi -lt $historyData.Count; $hi++) { $inc = $historyData[$hi]. Atualizado - $historyData[$hi-1]. Atualizado se ($inc -gt 0) { $increments += $inc } experimente { $d 1 = [datetime]::P arse($historyData[$hi-1]. Data) $d 2 = [datetime]::P arse($historyData[$hi]. Data) $gap = ($d 2 - $d 1). TotalDays se ($gap -gt 0) { $dayGaps += $gap } } captura {} } # Tamanho da onda = incremento positivo mais recente (onda atual), contingência para média, mínimo 2 $waveSize = se ($increments. Contagem -gt 0) { [matemática]::Máx.(2, $increments[-1]) } senão { 2 } # Período de observação = intervalo médio entre pontos de dados (dias de calendário por onda), mínimo de 1 $waveDays = se ($dayGaps.Count -gt 0) { [math]::Max(1, [math]::Round(($dayGaps | Measure-Object -Average). Média, 0)) } senão { 1 }
Write-Host " Projeção: waveSize=$waveSize (do último incremento), waveDays=$waveDays (intervalo médio da história)" -ForegroundColor DarkGray
$dayCounter = 0 # Project até todos os dispositivos serem atualizados ou 365 dias no máximo para ($pi = 1; $pi -le 365; $pi++) { $projDate = $projDate.AddDays(1) $dayCounter++ # Em cada limite do período de observação, implemente uma onda e, em seguida, duplique if ($dayCounter -ge $waveDays) { $devicesThisWave = [matemática]::Min($waveSize, $remaining) $lastUpdated += $devicesThisWave $remaining -= $devicesThisWave if ($lastUpdated -gt ($c.Updated + $stNotUptodate)) { $lastUpdated = $c.Updated + $stNotUptodate; $remaining = 0 } # Tamanho de onda duplo para o próximo período (estratégia 2x do orquestrador) $waveSize = $waveSize * 2 $dayCounter = 0 } $projDates += "'$($projDate.ToString("aaaa-MM-dd"))'" $projValues += $lastUpdated $projNotUpdValues += [matemática]::Máx.(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 " Projeção: precisa de pelo menos 2 pontos de dados de tendência para derivar o tempo de onda" -ForegroundColor DarkGray } # Criar cadeias de dados de gráfico combinadas para a cadeia here-string $allChartLabels = se ($hasProjection) { "$trendLabels,$projLabels" } senão { $trendLabels } $projDataJS = se ($hasProjection) { $projUpdated } senão { "" } $projNotUpdJS = se ($hasProjection) { $projNotUpdated } senão { "" } $histCount = ($historyData | Measure-Object). Contagem $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Descending | ForEach-Object { @{ name=$_. Chave; total=$_. Value.Total; updated=$_. Value.Updated; highConf=$_. Value.HighConf; actionReq=$_. Value.ActionReq } } | ConvertTo-Json -Profundidade 3 | Set-Content (Join-Path $dataDir "manufacturers.json") -Encoding UTF8 # Convert JSON data files to CSV for human-readable Excel downloads (Converter ficheiros de dados JSON em CSV para transferências do Excel legíveis por humanos) Write-Host "Converter dados do dispositivo em CSV para transferência do Excel..." -ForegroundColor Gray foreach ($dfName em $stDeviceFiles) { $jsonFile = Join-Path $dataDir "$dfName.json" $csvFile = Join-Path $OutputPath "SecureBoot_${dfName}_$timestamp.csv" if (Test-Path $jsonFile) { experimente { $jsonData = Get-Content $jsonFile -Raw | ConverterFrom-Json if ($jsonData.Count -gt 0) { # Incluir colunas adicionais para update_pending CSV $selectProps = se ($dfName -eq "update_pending") { @('HostName', 'WMI_Manufacturer', 'WMI_Model', 'BucketId', 'ConfidenceLevel', 'IsUpdated', 'UEFICA2023Status', 'UEFICA2023Error', 'AvailableUpdatesPolicy', 'WinCSKeyApplied', 'SecureBootTaskStatus') } senão { @('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 -> linhas $($jsonData.Count) -> CSV" -ForegroundColor DarkGray } } catch { Write-Host " $dfName - skipped" -ForegroundColor DarkYellow } } } # Gerar dashboard HTML autónomo $htmlPath = Join-Path $OutputPath "SecureBoot_Dashboard_$timestamp.html" Write-Host "Generating self-contained HTML dashboard..." -ForegroundColor Yellow # PROJEÇÃO DA VELOCIDADE: Calcular a partir do histórico de análises ou resumo anterior $stDeadline = [datetime]"2026-06-24" # KEK cert expiry $stDaysToDeadline = [matemática]::Max(0, ($stDeadline - (Get-Date)). Dias) $stDevicesPerDay = 0 $stProjectedDate = $null $stVelocitySource = "N/D" $stWorkingDays = 0 $stCalendarDays = 0 # Experimente primeiro o histórico de tendências (leve, já mantido pelo agregador — substitui o ScanHistory.json inchado) if ($historyData.Count -ge 2) { $validHistory = @($historyData | Where-Object { [int]$_. Total -gt 0 -e [int]$_. Atualizado -ge 0 }) if ($validHistory.Count -ge 2) { $prev = $validHistory[-2]; $curr = $validHistory[-1] $prevDate = [datetime]::P arse($prev. Date.Substring(0, [Matemática]::Min(10, $prev. Date.Length))) $currDate = [datetime]::P arse($curr. Date.Substring(0, [Matemática]::Min(10, $curr. Date.Length))) $daysDiff = ($currDate - $prevDate). TotalDays se ($daysDiff -gt 0) { $updDiff = [int]$curr. Atualizado - [int]$prev. Atualizado se ($updDiff -gt 0) { $stDevicesPerDay = [matemática]::Round($updDiff/$daysDiff, 0) $stVelocitySource = "TrendHistory" } } } } # Experimente o resumo da implementação do orquestrador (tem velocidade pré-calculada) if ($stVelocitySource -eq "N/A" -and $RolloutSummaryPath -and (Test-Path $RolloutSummaryPath)) { experimente { $rolloutSummary = Get-Content $RolloutSummaryPath -Raw | ConverterFrom-Json if ($rolloutSummary.DevicesPerDay -and [double]$rolloutSummary.DevicesPerDay -gt 0) { $stDevicesPerDay = [matemática]::Round([double]$rolloutSummary.DevicesPerDay, 1) $stVelocitySource = "Orchestrator" if ($rolloutSummary.ProjectedCompletionDate) { $stProjectedDate = $rolloutSummary.ProjectedCompletionDate } if ($rolloutSummary.WorkingDaysRemaining) { $stWorkingDays = [int]$rolloutSummary.WorkingDaysRemaining } if ($rolloutSummary.CalendarDaysRemaining) { $stCalendarDays = [int]$rolloutSummary.CalendarDaysRemaining } } } captura { } } # Contingência: experimente o CSV de resumo anterior (procurar pasta atual E pastas de agregação principal/colateral) if ($stVelocitySource -eq "N/A") { $searchPaths = @( (Join-Path $OutputPath "SecureBoot_Summary_*.csv") ) # Pesquise também pastas de agregação de elementos secundários (o orchestrator cria uma nova pasta em cada execução) $parentPath = Split-Path $OutputPath -Parent se ($parentPath) { $searchPaths += (Join-Path $parentPath "Aggregation_*\SecureBoot_Summary_*.csv") $searchPaths += (Join-Path $parentPath "SecureBoot_Summary_*.csv") } $prevSummary = $searchPaths | ForEach-Object { Get-ChildItem $_ -EA SilentlyContinue } | Sort-Object LastWriteTime -Descending | Select-Object -Primeiro 1 se ($prevSummary) { experimente { $prevStats = Get-Content $prevSummary.FullName | ConverterFrom-Csv $prevDate = [datetime]$prevStats.ReportGeneratedAt $daysSinceLast = ((Get-Date) - $prevDate). TotalDays if ($daysSinceLast -gt 0.01) { $prevUpdated = [int]$prevStats.Updated $updDelta = $c.Updated - $prevUpdated se ($updDelta -gt 0) { $stDevicesPerDay = [matemática]::Round($updDelta/$daysSinceLast, 0) $stVelocitySource = "PreviousReport" } } } captura { } } } # Contingência: calcular a velocidade do intervalo completo do histórico de tendências (primeiro vs. ponto de dados mais recente) if ($stVelocitySource -eq "N/A" -and $historyData.Count -ge 2) { $validHistory = @($historyData | Where-Object { [int]$_. Total -gt 0 -e [int]$_. Atualizado -ge 0 }) if ($validHistory.Count -ge 2) { $first = $validHistory[0] $last = $validHistory[-1] $firstDate = [datetime]::P arse($first. Date.Substring(0, [Matemática]::Min(10, $first. Date.Length))) $lastDate = [datetime]::P arse($last. Date.Substring(0, [Matemática]::Min(10, $last. Date.Length))) $daysDiff = ($lastDate - $firstDate). TotalDays se ($daysDiff -gt 0) { $updDiff = [int]$last. Atualizado - [int]$first. Atualizado se ($updDiff -gt 0) { $stDevicesPerDay = [matemática]::Round($updDiff/$daysDiff, 1) $stVelocitySource = "TrendHistory" } } } } # Calcular a projeção com duplicação exponencial (consistente com o gráfico de tendências) # Reutilize os dados de projeção já calculados para o gráfico, se disponíveis if ($hasProjection -and $projDates.Count -gt 0) { # Utilize a última data prevista (quando todos os dispositivos são atualizados) $lastProjDateStr = $projDates[-1] -replace "'", "" $stProjectedDate = ([datetime]::P arse($lastProjDateStr)). ToString("DD MMM, aaaa") $stCalendarDays = ([datetime]::P arse($lastProjDateStr) - (Get-Date)). Dias $stWorkingDays = 0 $d = Get-Date para ($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) { # Contingência: projeção linear se não existirem dados exponenciais disponíveis $daysNeeded = [matemática]::Teto($stNotUptodate/$stDevicesPerDay) $stProjectedDate = (Data de Obtenção). AddDays($daysNeeded). ToString("DD MMM, aaaa") $stWorkingDays = 0; $stCalendarDays = $daysNeeded $d = Data de Obtenção para ($i = 0; $i -lt $daysNeeded; $i++) { $d = $d.AddDays(1) if ($d.DayOfWeek -ne 'Saturday' -and $d.DayOfWeek -ne 'Sunday') { $stWorkingDays++ } } } # Build velocity HTML $velocityHtml = se ($stDevicesPerDay -gt 0) { "<div><strong>🚀 Devices/Day:</strong> $($stDevicesPerDay.ToString('N0')) (source: $stVelocitySource)</div>" + "<div><strong>📅 Conclusão Prevista:</strong> $stProjectedDate" + $(if ($stProjectedDate -and [datetime]::P arse($stProjectedDate) -gt $stDeadline) { " <span style='color:#dc3545; font-weight:bold'>⚠ PAST DEADLINE</span>" } else { " <span style='color:#28a745'>✓ Before deadline</span>" }) + "</div>" + "<div><strong>🕐 Dias Úteis:</strong> $stWorkingDays | <forte>Calendar Dias:</strong> $stCalendarDays</div>" + "<div style='font-size:.8em; color:#888'>Deadline: 24 de junho de 2026 (expiração do certificado KEK) | Dias restantes: $stDaysToDeadline</div>" } senão { "<div style='padding:8px; background:#fff3cd; border-radius:4px; border-left:3px solid #ffc107'>" + "<forte>📅 Conclusão Prevista:</strong> Dados insuficientes para cálculos de velocidade. " + "Execute a agregação pelo menos duas vezes com alterações de dados para estabelecer uma taxa.<br/>" + "<forte>Deadline:</strong> 24 de junho de 2026 (expiração do certificado KEK) | <dias>fortes restantes:</strong> $stDaysToDeadline</div>" } # Contagem decrescente de expiração do certificado $certToday = Data de Obtenção $certKekExpiry = [datetime]"2026-06-24" $certUefiExpiry = [datetime]"2026-06-27" $certPcaExpiry = [datetime]"2026-10-19" $daysToKek = [matemática]::Max(0, ($certKekExpiry - $certToday). Dias) $daysToUefi = [matemática]::Max(0, ($certUefiExpiry - $certToday). Dias) $daysToPca = [matemática]::Max(0, ($certPcaExpiry - $certToday). Dias) $certUrgency = se ($daysToKek -lt 30) { '#dc3545' } elseif ($daysToKek -lt 90) { '#fd7e14' } else { '#28a745' } # Helper: Read records from JSON, build bucket summary + first N device rows $maxInlineRows = 200 função Build-InlineTable { parâmetro([string]$JsonPath, [int]$MaxRows = 200, [string]$CsvFileName = "") $bucketSummary = "" $deviceRows = "" $totalCount = 0 if (Test-Path $JsonPath) { experimente { $data = Get-Content $JsonPath -Raw | ConverterFrom-Json $totalCount = $data. Contagem # BUCKET SUMMARY: Group by BucketId, show counts per bucket with Updated from global bucket stats se ($totalCount -gt 0) { $buckets = $data | Group-Object BucketId | Contagem de Sort-Object -Descendente $bucketSummary = "><2 h3 style='font-size:.95em; color:#333; margin:10px 0 5px'><3 By Hardware Bucket ($($buckets. Contagem) registos)><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'>Atualizado</th><th style='text-align:right; color:#dc3545'>Not Updated</th><th><1 Manufacturer><2 /th></tr></thead><tbody>" foreach ($b no $buckets) { $bid = se ($b.Name) { $b.Name } senão { "(vazio)" } $mfr = ($b.Group | Select-Object -First 1). WMI_Manufacturer # Obter a contagem atualizada a partir de estatísticas de registo global (todos os dispositivos neste registo em todo o conjunto de dados) $lookupKey = $bid $globalBucket = se ($stAllBuckets.ContainsKey($lookupKey)) { $stAllBuckets[$lookupKey] } senão { $null } $bUpdatedGlobal = se ($globalBucket) { $globalBucket.Updated } senão { 0 } $bTotalGlobal = se ($globalBucket) { $globalBucket.Count } senão { $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; color:#28a745; font-weight:bold'>$bUpdatedGlobal><2 /td><td style='text-align:right; color:#dc3545; font-weight:bold'>$bNotUpdatedGlobal><6 /td><td><9 $mfr</td></tr>'n' } $bucketSummary += "</tbody></table></div>" } # DETALHE DO DISPOSITIVO: Primeiras N linhas como lista simples $slice = $data | Select-Object -Primeira $MaxRows foreach ($d no $slice) { $conf = $d.ConfidenceLevel $confBadge = se ($conf -match "High") { '<span class="badge-success">High Conf><2 /span>' } elseif ($conf -match "Not Sup") { '<span class="badge-danger">Not Supported><6 /span>' } elseif ($conf -match "Under") { '<span class="badge-info">Under Obs><0 /span>' } elseif ($conf -match "Paused") { '<span class="badge-warning">em pausa><4 /span>' } else { '<span class="badge-warning">Action Req><8 /span>' } $statusBadge = se ($d.IsUpdated) { '><00 span class="badge-success"><01 Updated</span>' } elseif ($d.UEFICA2023Error) { '><04 span class="badge-danger"><05 Error</span>' } else { '><08 span class="badge-warning"><09 Pendente><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 /td><td><5 $(if($d.UEFICA2023Error){$d.UEFICA2023Error}else{'-'})$d.UEFICA2023Error}else{'-'})><36 $d /td><td style='font-size:.75em'><39 $($d.BucketId)><40 /td></tr><3 'n' } } captura { } } if ($totalCount -eq 0) { devolver "><44 div style='padding:20px; color:#888; font-style:itálico'><45 Nenhum dispositivo nesta categoria.><46 /div>" } $showing = [matemática]::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'>📄 Transferir o CSV Completo para Excel><3 /a>" } $header += "><55 /div>" $deviceHeader = "><57 h3 style='font-size:.95em; color:#333; margin:10px 0 5px'><58 Device Details (showing first $showing)><59 /h3>" $deviceTable = "><61 div style='max-height:500px; overflow-y:auto'><table><thead><tr><th><0 HostName><1 /th><th><4 Manufacturer><5 /th><th><8 Model><9 /th><th><2 Confidence><3 /th><Estado do><6><7 /th><th><0 Error><1 /th><th><4 BucketId><5 /th></tr></thead><tbody><2 $deviceRows><3 /tbody></table></div>" devolver "$header$bucketSummary$deviceHeader$deviceTable" } # Crie tabelas inline a partir dos ficheiros JSON já existentes no disco, ligando a CSVs $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" # Tabela personalizada para Atualização Pendente — inclui as colunas UEFICA2023Status e UEFICA2023Error $tblUpdatePending = "" $upJsonPath = Join-Path $dataDir "update_pending.json" if (Test-Path $upJsonPath) { experimente { $upData = Get-Content $upJsonPath -Raw | ConverterFrom-Json $upCount = $upData.Count se ($upCount -gt 0) { $upHeader = "<div style='margin:5px 0; font-size:.85em; color:#666'>Total: $($upCount.ToString("N0")) dispositivos | <a href='SecureBoot_update_pending_$timestamp.csv' style='color:#1a237e; font-weight:bold'>📄 Transferir o CSV Completo para Excel><4 /a></div>" $upRows = "" $upSlice = $upData | Select-Object -Primeira $maxInlineRows foreach ($d no $upSlice) { $uefiSt = se ($d.UEFICA2023Status) { $d.UEFICA2023Status } else { '<span style="color:#999">null><0 /span>' } $uefiErr = se ($d.UEFICA2023Error) { "<span style='color:#dc3545'>$($d.UEFICA2023Error)</span>" } else { '-' } $policyVal = se ($d.AvailableUpdatesPolicy) { $d.AvailableUpdatesPolicy } else { '-' } $wincsVal = se ($d.WinCSKeyApplied) { '<span class="badge-success">Yes><8 /span>' } else { '-' } $upRows += "<tr><td><3 $($d.HostName)</td><td><7 $($d.WMI_Manufacturer)</td><td><1 $($d.WMI_Model)</td><td><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 = [matemática]::Min($maxInlineRows, $upCount) $upDevHeader = "<h3 style='font-size:.95em; color:#333; margin:10px 0 5px'>Device Details (mostrando o primeiro $upShowing)</h3>" $upTable = "<div style='max-height:500px; overflow-y:auto'><table><thead><tr><th><9 HostName><0 /th><th><3 Manufacturer><4 /th th><th><7 Model><8 /th><th><1 UEFICA2023Status><2 /th><th><5 UEFICA2023Erro><6 /th><th><9 Policy</th><th>WinCS Key</th><thth>BucketId</th></tr></thead><tbody><5 $upRows><6 /tbody></table></div>" $tblUpdatePending = "$upHeader$upDevHeader$upTable" } senão { $tblUpdatePending = "<div style='padding:20px; color:#888; font-style:itálico'>Nenhum dispositivo nesta categoria.</div>" } } captura { $tblUpdatePending = "<div style='padding:20px; color:#888; font-style:itálico'>Nenhum dispositivo nesta categoria.</div>" } } senão { $tblUpdatePending = "<div style='padding:20px; color:#888; font-style:itálico'>Nenhum dispositivo nesta categoria.</div>" } # Contagem decrescente de expiração do certificado $certToday = Data de Obtenção $certKekExpiry = [datetime]"2026-06-24" $certUefiExpiry = [datetime]"2026-06-27" $certPcaExpiry = [datetime]"2026-10-19" $daysToKek = [matemática]::Max(0, ($certKekExpiry - $certToday). Dias) $daysToUefi = [matemática]::Max(0, ($certUefiExpiry - $certToday). Dias) $daysToPca = [matemática]::Max(0, ($certPcaExpiry - $certToday). Dias) $certUrgency = se ($daysToKek -lt 30) { '#dc3545' } elseif ($daysToKek -lt 90) { '#fd7e14' } else { '#28a745' } # Criar dados de gráficos do fabricante inline (Top 10 por contagem de dispositivos) $mfrSorted = $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Descending | Select-Object -Primeiros 10 $mfrChartTitle = se ($stMfrCounts.Count -le 10) { "By Manufacturer" } else { "Top 10 Manufacturers" } $mfrLabels = ($mfrSorted | ForEach-Object { "'$($_. Chave)'" }) -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 "," # Criar tabela do fabricante $mfrTableRows = "" $stMfrCounts.GetEnumerator() | Sort-Object { $_. Value.Total } -Descending | ForEach-Object { $mfrTableRows += "<tr><td><7 $($_. Chave)</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 da cabeça < <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <título><9 Dashboard de Estado do Certificado de Arranque Seguro><0 /title><1 <script src="https://cdn.jsdelivr.net/npm/chart.js"></script><5 ><7 de estilo < *{box-sizing:border-box; margin:0; preenchimento:0} body{font-family:'Segoe UI',Tahoma,sans-serif; background:#f0f2f5; color:#333} .header{background:linear-gradient(135deg,#1a237e,#0d47a1); color:#fff; preenchimento:20px 30px} .header h1{font-size:1.6em; margem inferior:5px} .header .meta{font-size:.85em; opacidade:.9} .container{max-width:1400px; margin:0 auto; preenchimento:20px} .cards{display:grid; grid-template-columns:repeat(auto-fill,minmax(170px,1fr)); gap:12px; margin:20px 0} .card{background:#fff; border-radius:10px; preenchimento:15px; box-shadow:0 2px 8px rgba(0,0,0,.08); limite à esquerda:4px sólido #ccc;transição:transformar .2s} .card:hover{transform:translateY(-2px); box-shadow:0 4px 15px rgba(0,0,0,.12)} .card .value{font-size:1.8em; espessura do tipo de letra:700} .card .label{font-size:.8em; color:#666; margin-top:4px} .card .pct{font-size:.75em; color:#888} .section{background:#fff; border-radius:10px; preenchimento:20px; margin:15px 0; box-shadow:0 2px 8px rgba(0,0,0,.08)} .section h2{font-size:1.2em; color:#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; margin:20px 0} .chart-box{background:#fff; border-radius:10px; preenchimento:20px; box-shadow:0 2px 8px rgba(0,0,0,.08)} tabela{width:100%; border-collapse:collapse; font-size:.85em} th{background:#e8eaf6; preenchimento:8px 10px; alinhar o texto:esquerda; posição:sticky; top:0; z-index:1} td{padding:6px 10px; limite inferior:1px sólido #eee} tr:hover{background:#f5f5f5} .badge{display:inline-block; preenchimento:2px 8px;border-radius:10px; font-size:.75em; espessura do tipo de letra:700} .badge-success{background:#d4edda; color:#155724} .badge-danger{background:#f8d7da; color:#721c24} .badge-warning{background:#fff3cd; color:#856404} .badge-info{background:#d1ecf1; color:#0c5460} .top-link{float:right; font-size:.8em; color:#1a237e; text-decoration:none} .footer{text-align:center; preenchimento:20px; color:#999; font-size:.8em} a{color:#1a237e} </style><9 </head> <corpo> <div class="header"> <h1>Dashboard de Estado do Certificado de Arranque Seguro</h1> <div class="meta">Gerado: $($stats. ReportGeneratedAt) | Total de Dispositivos: $($c.Total.ToString("N0")) | Registos Exclusivos: $($stAllBuckets.Count)</div><3 </div><5 <div class="container">
<!-- cartões KPI - clicáveis, ligados a secções - > <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; direita:8px; background:#dc3545; color:#fff; preenchimento:1px 6px; border-radius:8px; font-size:.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)% - PRECISA DE AÇÃO><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; direita:8px; background:#28a745; color:#fff; preenchimento:1px 6px; border-radius:8px; font-size:.65em; font-weight:700">PRIMARY><8 /div><div class="value" style="color:#28a745">$($c.Updated.ToString()"N0"))</div><div class="label">Updated><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; direita:8px; background:#6c757d; color:#fff; preenchimento:1px 6px; border-radius:8px; font-size:.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})% - Fora do Âmbito><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){[matemática]::Round(($c.NeedsReboot/$c.Total)*100,1)}senão{0})% - a aguardar reinício><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">UpdatePending</div<><div class="pct">$(if($c.Total -gt 0){[math]::Round(($c.UpdatePending/$c.Total)*100,1)}else{0})% - Política/WinCS aplicada, a aguardar atualização><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.RolloutInProgress)</div><div class="label">Rollout In Progress><4 /div><div class="pct"><<$(if($c.Total -gt 0){[matemática]::Round(($c.RolloutInProgress/$c.Total)*100,1)}senão{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)% - Seguro para implementação><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){[matemática]::Round(($c.UnderObs/$c.Total)*100,1)}senão{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)% - tem de testar><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)% - Semelhante a><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){[matemática]::Round(($c.TaskDisabled/$c.Total)*100,1)}senão{0})% - Bloqueado><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. Pausada</div><div class="pct">$(if($c.Total -gt 0){[matemática]::Round(($c.TempPaused/$c.Total)*100,1)}senão{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){[matemática]::Round(($c.WithKnownIssues/$c.Total)*100,1)}senão{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 em falta</div><div class="pct">$(if($c.Total -gt 0){[matemática]::Round(($c.WithMissingKEK/$c.Total)*100,1)}senão{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)% - Erros 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. Falhas</div><div class="pct">$(if($c.Total -gt 0){[matemática]::Round(($c.TempFailures/$c.Total)*100,1)}senão{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){[matemática]::Round(($c.PermFailures/$c.Total)*100,1)}else{0})%</div></a><3 </div>
<!-- Cert Expiração da Velocidade de Implementação & --> <div id="s-velocity" style="display:grid; grid-template-columns:1fr 1fr; gap:20px; margin:15px 0"> <div class="section" style="margin:0"> <h2>📅 Deployment Velocity</h2> <div class="section-body open"> <div style="font-size:2.5em; espessura do tipo de letra:700; color:#28a745">$($c.Updated.ToString("N0"))</div> <div style="color:#666">dispositivos atualizados a partir de $($c.Total.ToString("N0"))</div> <div style="margin:10px 0; background:#e8eaf6; height:20px; border-radius:10px; overflow:hidden"><div style="background:#28a745; altura:100%; width:$($stats. PercentCertUpdated)%; border-radius:10px"></div></div> <div style="font-size:.8em; color:#888">$($stats. PercentCertUpdated)% concluído</div> <div style="margin-top:10px; preenchimento:10px; background:#f8f9fa; border-radius:8px; font-size:.85em"> <div><forte>Restante:</strong> $($stNotUptodate.ToString("N0")) os dispositivos precisam de ação</div> <div><forte>Bloqueio:</strong> $($c.WithErrors + $c.PermFailures + $c.TaskDisabledNotUpdated) (erros + permanente + tarefa desativada)</div> <div><strong>Safe to deploy:</strong> $($stSafeList.ToString("N0")) devices (same bucket as successful)</div> $velocityHtml </div> </div> </div> <div class="section" style="margin:0; limite à esquerda:4px #dc3545 sólido"> <h2 style="color:#dc3545">⚠ Contagem deCrescente de Expiração do Certificado</h2> <div class="section-body open"> <div style="display:flex; gap:15px; margin-top:10px"> <div style="text-align:center; preenchimento:15px; border-radius:8px; largura mínima:120px; background:linear-gradient(135deg,#fff5f5,#ffe0e0); limite:2px #dc3545 sólido; flex:1"> <div style="font-size:.65em; color:#721c24; text-transform:uppercase; font-weight:bold">⚠ FIRST TO EXPIRE</div> ><4 div style="font-size:.85em; espessura do tipo de letra:negrito; color:#dc3545; margin:3px 0"><5 KEK CA 2011</div> ><8 div id="daysKek" style="font-size:2.5em; espessura do tipo de letra:700; color:#dc3545; altura da linha:1"><9 $daysToKek</div> ><2 div style="font-size:.8em; color:#721c24"><3 dias (24 de junho de 2026)><4 /div> ><6 /div> ><8 div style="text-align:center; preenchimento:15px; border-radius:8px; largura mínima:120px; background:linear-gradient(135deg,#fffef5,#fff3cd); limite:2px #ffc107 sólido; flex:1"><9 <div style="font-size:.65em; color:#856404; text-transform:uppercase; font-weight:bold">CA UEFI 2011</div> <div id="daysUefi" style="font-size:2.2em; espessura do tipo de letra:700; color:#856404; altura da linha:1; margin:5px 0">$daysToUefi</div> <div style="font-size:.8em; color:#856404">dias (27 de junho de 2026)</div> </div> <div style="text-align:center; preenchimento:15px; border-radius:8px; largura mínima:120px; background:linear-gradient(135deg,#f0f8ff,#d4edff); limite:2px #0078d4 sólido; flex:1"> <div style="font-size:.65em; color:#0078d4; text-transform:uppercase; font-weight:bold">PCA do Windows</div> <div id="daysPca" style="font-size:2.2em; espessura do tipo de letra:700; color:#0078d4; altura da linha:1; margin:5px 0">$daysToPca><2 /div><3 <div style="font-size:.8em; color:#0078d4">dias (19 de outubro de 2026)</div><7 </div><9 </div><1 <div style="margin-top:15px; preenchimento:10px; background:#f8d7da; border-radius:8px; font-size:.85em; limite esquerdo:4px solid #dc3545"> <forte>⚠ CRITICAL:</strong> Todos os dispositivos têm de ser atualizados antes da expiração do certificado. Os dispositivos não atualizados até ao prazo não podem aplicar futuras Atualizações de segurança para o Gestor de Arranque e o Arranque Seguro após a expiração.</div> </div> </div> </div>
Gráficos de<!-- --> <div class="charts"> <div class="chart-box"><h3>Deployment Status</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) { "<!-- Gráfico de Tendências Históricas --> <div class='section'> <h2 onclick='"toggle('d-trend')'">📈 Atualizar o Progresso ao Longo do Tempo <uma classe='top-link' href='#'>↑ Top</a></h2> <div id='d-trend' class='section-body open'> <id de tela='trendChart' height='120'></canvas> <div style='font-size:.75em; color:#888; margin-top:5px'>Linhas sólidas = dados reais$(se ($historyData.Count -ge 2) { " | Linha tracejada = projetada (duplicação exponencial: 2→4→8→16... dispositivos por onda)" } senão { " | Execute novamente a agregação amanhã para ver as linhas de tendência e a projeção" })</div> </div> </div>" })
<!-- transferências CSV --> <div class="section"> <h2 onclick="toggle('dl-csv')">📥 Transferir Dados Completos (CSV para Excel) <uma classe="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; background:#dc3545; color:#fff; preenchimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Não Atualizado ($($stNotUptodate.ToString("N0")))</a><8 <a href="SecureBoot_errors_$timestamp.csv" style="display:inline-block; background:#dc3545; color:#fff; preenchimento: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; background:#fd7e14; color:#fff; preenchimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Ação Necessária ($($c.ActionReq.ToString("N0")</a> <a href="SecureBoot_known_issues_$timestamp.csv" style="display:inline-block; background:#dc3545; color:#fff; preenchimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Problemas Conhecidos ($($c.WithKnownIssues.ToString("N0")))</a> <a href="SecureBoot_task_disabled_$timestamp.csv" style="display:inline-block; background:#dc3545; color:#fff; preenchimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Tarefa Desativada ($($c.TaskDisabled.ToString("N0")))</a> <a href="SecureBoot_updated_devices_$timestamp.csv" style="display:inline-block; background:#28a745; color:#fff; preenchimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Atualizado ($($c.Updated.ToString("N0")))</a> <a href="SecureBoot_Summary_$timestamp.csv" style="display:inline-block; background:#6c757d; color:#fff; preenchimento:6px 14px; border-radius:5px; text-decoration:none; font-size:.8em">Resumo</a> <div style="width:100%; font-size:.75em; color:#888; margin-top:5px">ficheiros CSV abertos no Excel. Disponível quando alojado no servidor Web.</div> </div> </div>
<!-- Divisão do Fabricante --> <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"> <tabela><thead><tr><th><1 Manufacturer><2 /th><th><5 Total><6 /th><th><9 Updated><9><0 /th><th><3 High Confidence><4 /th><th><7 Action Required><8 /th></tr></thead><3 <tbody><5 $mfrTableRows><6 /tbody></table><9 </div><1 </div>
<!-- Secções de Dispositivos (primeiras 200 inline + transferência CSV) --> <div class="section" id="s-err"> <h2 onclick="toggle('d-err')">🔴 Dispositivos com Erros ($($c.WithErrors.ToString("N0"))) <uma classe="top-link" href="#">↑</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">🔴 Problemas Conhecidos ($($c.WithKnownIssues.ToString("N0"))) <a class="top-link" href="#">↑ top</a></h2> <div id="d-ki" class="section-body">$tblKI</div> </div> <div class="section" id="s-kek"> <h2 onclick="toggle('d-kek')">🟠 KEK em falta - Evento 1803 ($($c.WithMissingKEK.ToString("N0"))) <a class="top-link" href="#">↑ top</a></h2> >↑ 0 div id="d-kek" class="section-body">↑ 1 $tblKEK</div> >↑ 4 /div> >↑ 6 div class="section" id="s-ar">↑ 7 >↑ 8 h2 onclick="toggle('d-ar')" style="color:#fd7e14">🟠 Ação Necessária ($($c.ActionReq.ToString("N0"))) <a class="top-link" href="#">↑ 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">🔵 Em Observação ($($c.UnderObs.ToString("N0"))) <a class="top-link" href="#">↑ 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">🔴 Não Atualizado ($($stNotUptodate.ToString("N0"))) <uma classe="top-link" href="#">↑ principais</a></h2> <div id="d-nu" class="section-body">$tblNotUpd</div> </div> >↑ 0 div class="section" id="s-td">↑ 1 >↑ 2 h2 onclick="toggle('d-td')" style="color:#dc3545">🔴 Tarefa Desativada ($($c.TaskDisabled.ToString("N0"))) >↑ 5 a class="top-link" href="#">↑ top</a></h2><1 <div id="d-td" class="section-body">$tblTaskDis><4 /div><5 </div><7 <div class="section" id="s-tf"> <h2 onclick="toggle('d-tf')" style="color:#dc3545">🔴 Falhas Temporárias ($($c.TempFailures.ToString("N0"))) <uma classe="top-link" href="#">↑</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">🔴 Falhas Permanentes/Não Suportadas ($($c.PermFailures.ToString("N0"))) <uma classe="top-link" href="#">↑ 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">⏳ Update Pending ($($c.UpdatePending.ToString("N0"))) - Política/WinCS Aplicado, A aguardar Atualização <uma classe="top-link" href="#">↑ top</a></h2> <div id="d-upd-pend" class="section-body"><p style="color:#666; margin-bottom:10px">Devices where AvailableUpdatesPolicy or WinCS key is applied but UEFICA2023Status is still NotStarted, InProgress, or null.</p>$tblUpdatePending</div> </div> <div class="section" id="s-rip"> <h2 onclick="toggle('d-rip')" style="color:#17a2b8">🔵 Implementação em Curso ($($c.RolloutInProgress.ToString("N0"))) <a class="top-link" href="#">↑ 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">⚫ SecureBoot OFF ($($c.SBOff.ToString("N0"))) - Fora do Âmbito <a class="top-link" href="#">↑ 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">🟢 Dispositivos Atualizados ($($c.Updated.ToString("N0"))) <uma classe="top-link" href="#">↑ 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">🔄 Atualizado - Precisa de Reiniciar ($($c.NeedsReboot.ToString("N0"))) <uma classe="top-link" href="#">↑</a></h2> <div id="d-nrb" class="section-body">$tblNeedsReboot</div> </div>
<div class="footer" >Dashboard de Implementação de Certificados de Arranque Seguro | $($stats gerados). ReportGeneratedAt) | StreamingMode | Memória de Pico: ${stPeakMemMB} MB</div> </div><!-- /container -->
<script> function toggle(id){var e=document.getElementById(id); e.classList.toggle('open')} function openSection(id){var e=document.getElementById(id); if(e&&!e.classList.contains('open')){e.classList.add('open')}} new Chart(document.getElementById('deployChart'),{type:'donut',data:{labels:['Updated','Update Pending','High Confidence','Under Observation','Action Required','Temp. Em pausa','Não Suportado','SecureBoot OFF','Com Erros'],conjuntos de dados:[{data:[$($c.Updated),$($c.UpdatePending),$($c.HighConf),$($c.UnderObs),$($c.ActionReq),$($c.TempPaused),$($c.NotSupported),$($c.SBOff),$($c.WithErrors)],backgroundColor:['#28a745','#6f42c1','#20c997','#17a2b8','#fd7e14','#6c757d','#6c757d','#17a2b8', #721c24','#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. Em pausa',dados:[$mfrTempPaused],backgroundColor:'#6c757d'},{label:'Not Supported',data:[$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'}}}); Gráfico de Tendências Históricas 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 = Matriz(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] = actualNotUpdData[histLen-1]; projNotUpdLine = projNotUpdLine.concat(projNotUpdData); } conjuntos de dados var = [ {label:'Updated',data:paddedUpdated,borderColor:'#28a745',backgroundColor:'rgba(40,167,69,0.1)',fill:true,tension:0.3,borderWidth:2}, {label:'Not Updated',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 (duplicação 2x)',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'}); } novo Gráfico(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'}}}); } Contagem decrescente dinâmica (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)) # Mantenha sempre uma cópia "Mais Recente" estável para que os administradores não precisem de controlar os carimbos de data/hora $latestPath = Join-Path $OutputPath "SecureBoot_Dashboard_Latest.html" Copy-Item $htmlPath $latestPath -Force $stTotal = $streamSw.Elapsed.TotalSeconds # Guarde o manifesto de ficheiro para o modo incremental (deteção rápida sem alterações na próxima execução) 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 "A guardar o manifesto de ficheiro para o modo incremental..." -ForegroundColor Gray foreach ($jf em $jsonFiles) { $stNewManifest[$jf. FullName.ToLowerInvariant()] = @{ LastWriteTimeUtc = $jf. LastWriteTimeUtc.ToString("o") Tamanho = $jf. Comprimento } } Save-FileManifest -$stNewManifest de Manifesto - $stManifestPath de Caminho Write-Host " Manifesto guardado para ficheiros $($stNewManifest.Count)" -ForegroundColor DarkGray } # LIMPEZA DA RETENÇÃO # Pasta reutilizável do Orchestrator (Aggregation_Current): mantenha apenas a última execução (1) # Administração execuções manuais/outras pastas: manter as últimas 7 execuções # Os CSVs de Resumo NUNCA são eliminados — são minúsculos (~1 KB) e são a origem de cópia de segurança do histórico de tendências $outputLeaf = Split-Path $OutputPath -Leaf $retentionCount = se ($outputLeaf -eq 'Aggregation_Current') { 1 } senão { 7 } # Prefixos de ficheiro seguros para limpar (instantâneos efémeros por execução) $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_' ) # Localizar todos os carimbos de data/hora exclusivos apenas a partir de ficheiros limpos $cleanableFiles = Get-ChildItem $OutputPath -File -EA SilentlyContinue | Where-Object { $f = $_. Nome; ($cleanupPrefixes | Where-Object { $f.StartsWith($_) }). Contagem -gt 0 } $allTimestamps = @($cleanableFiles | ForEach-Object { se ($_. Name -match '(\d{8}-\d{6})') { $Matches[1] } } | Sort-Object -Unique -Descending) if ($allTimestamps.Count -gt $retentionCount) { $oldTimestamps = $allTimestamps | Select-Object -Ignorar $retentionCount $removedFiles = 0; $freedBytes = 0 foreach ($oldTs no $oldTimestamps) { foreach ($prefix no $cleanupPrefixes) { $oldFiles = Get-ChildItem $OutputPath -File -Filter "${prefix}${oldTs}*" -EA SilentlyContinue foreach ($f em $oldFiles) { $freedBytes += $f.Length Remove-Item $f.FullName -Force -EA SilentlyContinue $removedFiles++ } } } $freedMB = [matemática]::Round($freedBytes/ 1 MB, 1) Write-Host "Limpeza da retenção: ficheiros $removedFiles removidos de execuções antigas $($oldTimestamps.Count), ${freedMB} MB (mantendo o último $retentionCount + todos os CSVs Summary/NotUptodate)" -ForegroundColor DarkGray } Write-Host "'n$("=" * 60)" -ForegroundColor Cyan Write-Host "AGREGAÇÃO DE TRANSMISSÃO EM FLUXO CONCLUÍDA" -Primeiro PlanoColor Verde Write-Host ("=" * 60) -ForegroundColor Cyan Write-Host " Total de Dispositivos: $($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 " Atualizado: $($c.Updated.ToString("N0")) ($($stats. PercentCertUpdated)%)" -ForegroundColor Green Write-Host " Com Erros: $($c.WithErrors.ToString("N0"))" -ForegroundColor $(if ($c.WithErrors -gt 0) { "Red" } else { "Green" }) Write-Host " Memória de Pico: ${stPeakMemMB} MB" -ForegroundColor Cyan Write-Host " Time: $([math]::Round($stTotal/60,1)) min" -ForegroundColor White Write-Host " Dashboard: $htmlPath" -ForegroundColor White return [PSCustomObject]$stats } #ENDREGION MODO DE TRANSMISSÃO EM FLUXO } senão { Write-Error "Caminho de entrada não encontrado: $InputPath" sair 1 }