<# .TITLE BitLocker Key Escrow Monitor .SYNOPSIS Inventory every Windows device in Intune, verify that a BitLocker recovery key is escrowed in Entra ID, keep a snapshot in Azure Storage at each run, detect what changed since the previous snapshot and e-mail a detailed HTML report (+ CSV / full HTML attachments). .DESCRIPTION Bulk retrieval of recovery-key METADATA (the key itself is never read): one paged call for the whole tenant instead of slow per-device loops. No Format-Table / Write-Information: the Azure Automation job output is no longer cropped. First run (no snapshot in storage) -> detailed BASELINE report. Next runs -> DELTA report: new devices, removed devices, re-enrolments, keys lost / escrowed / rotated, encryption changes, devices that stopped syncing... Snapshots: /snapshots/yyyy/MM/bitlocker-snapshot-.json + snapshots/latest.json Reports: /reports/yyyy/MM/ (HTML + CSV) latest.json is only updated after the e-mail has been sent successfully, so a failed run never "eats" a delta. If the device count suddenly drops by more than 50 %, latest.json is NOT updated (protection against partial Graph results). Pure REST in Azure Automation (no Graph module needed) - compatible PowerShell 5.1 and 7.x. -DemoMode $true generates a fake tenant offline to preview the reports without any permission. ENCRYPTED KEY BACKUP: the recovery key VALUES are exported to a separate container (/escrow/yyyy/MM/.bitlockerbackup.json), encrypted with AES-256 + HMAC, the AES key being wrapped with the PUBLIC key of an offline certificate (RSA-OAEP). The runbook can encrypt but can NEVER decrypt: only the PFX kept offline can. Key values never appear in the reports, the e-mail body, the snapshot or the job output. .TAGS Monitoring,Security,BitLocker,Intune .PERMISSIONS Managed identity of the Automation Account - Microsoft Graph APPLICATION permissions: DeviceManagementManagedDevices.Read.All BitlockerKey.Read.All (key VALUES - required for the encrypted backup) (BitlockerKey.ReadBasic.All is enough if -BackupRecoveryKeys $false) Device.Read.All (optional - Entra enrichment + orphan keys) Mail.Send (scope it with Exchange RBAC for Applications) Azure RBAC: Storage Blob Data Contributor on the report container AND on the key backup container Automation variable (not encrypted - it is a PUBLIC key): BitLockerBackupCert = base64 of the backup certificate .cer (New-BitLockerBackupCertificate.ps1) .AUTHOR MSEndpoint Engineering .VERSION 1.0 .CHANGELOG 1.0 - Public release: bulk key metadata, Azure Storage snapshots + delta, detailed HTML report, scheduled e-mail with attachments, throttling-aware Graph calls, demo mode, and offline RSA-OAEP + AES-256 encrypted recovery key escrow. .LASTUPDATE 2026-11-18 .EXAMPLE # Azure Automation (schedule parameters) Recipients = bitlocker-alerts@contoso.com SenderUPN = automation@contoso.com StorageAccountName = .EXAMPLE # Local preview of the reports with fake data (no connection, no permission) .\check-bitlocker-keys.ps1 -DemoMode $true .EXAMPLE # Local real run (interactive sign-in, snapshots kept in .\BitLockerReports) .\check-bitlocker-keys.ps1 -SendMail $false .NOTES Runbook: aa-contoso-intune / check-bitlocker-keys - Runtime PowerShell 5.1 This file is pure ASCII on purpose (PowerShell 5.1 + runbook editor encoding safety). #> [CmdletBinding()] param( [Parameter(Mandatory = $false)] [string]$Recipients = "bitlocker-alerts@contoso.com", [Parameter(Mandatory = $false)] [string]$SenderUPN = "automation@contoso.com", [Parameter(Mandatory = $false)] [string]$StorageAccountName = "stcontosointune", [Parameter(Mandatory = $false)] [string]$ContainerName = "bitlocker-reports", [Parameter(Mandatory = $false)] [string]$TenantLabel = "Contoso Corp", [Parameter(Mandatory = $false)] [ValidateRange(1, 365)] [int]$StaleDays = 30, [Parameter(Mandatory = $false)] [bool]$SendMail = $true, [Parameter(Mandatory = $false)] [bool]$MailOnlyWhenChanges = $false, [Parameter(Mandatory = $false)] [bool]$AttachFullHtml = $true, [Parameter(Mandatory = $false)] [bool]$ForceBaseline = $false, [Parameter(Mandatory = $false)] [bool]$IncludeEntraDevices = $true, [Parameter(Mandatory = $false)] [ValidateRange(10, 500)] [int]$MaxEmailRows = 50, [Parameter(Mandatory = $false)] [string]$CsvDelimiter = ";", [Parameter(Mandatory = $false)] [string]$TimeZoneId = "Romance Standard Time", [Parameter(Mandatory = $false)] [string]$ManagedIdentityClientId = "", [Parameter(Mandatory = $false)] [string]$OutputPath = "", [Parameter(Mandatory = $false)] [bool]$DemoMode = $false, [Parameter(Mandatory = $false)] [bool]$BackupRecoveryKeys = $true, [Parameter(Mandatory = $false)] [string]$KeyBackupContainer = "bitlocker-escrow", [Parameter(Mandatory = $false)] [string]$KeyBackupCertificate = "", [Parameter(Mandatory = $false)] [bool]$AttachKeyBackupToMail = $false ) Set-StrictMode -Off # Clean parameters typed in the portal (trailing spaces, upper case...) $StorageAccountName = ([string]$StorageAccountName).Trim().ToLowerInvariant() $ContainerName = ([string]$ContainerName).Trim().ToLowerInvariant() $KeyBackupContainer = ([string]$KeyBackupContainer).Trim().ToLowerInvariant() $Recipients = ([string]$Recipients).Trim() $SenderUPN = ([string]$SenderUPN).Trim() $KeyBackupCertificate = ([string]$KeyBackupCertificate).Trim() $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' try { [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 } catch { } $ScriptVersion = '1.0' $script:Stopwatch = [System.Diagnostics.Stopwatch]::StartNew() $script:GraphToken = $null $script:StorageToken = $null $script:UseMgGraph = $false $script:UseBlob = $false $script:StorageError = '' $script:LocalStoreDir = $null $script:Invariant = [System.Globalization.CultureInfo]::InvariantCulture $script:F = "font-family:Segoe UI,Segoe,Helvetica,Arial,sans-serif;" $script:IsAzureAutomation = $false if ($PSPrivateMetadata -and $PSPrivateMetadata.JobId -and $PSPrivateMetadata.JobId.Guid) { $script:IsAzureAutomation = $true } elseif ($env:AUTOMATION_ASSET_ACCOUNTID) { $script:IsAzureAutomation = $true } try { $script:TZ = [System.TimeZoneInfo]::FindSystemTimeZoneById($TimeZoneId) } catch { try { $script:TZ = [System.TimeZoneInfo]::FindSystemTimeZoneById('Europe/Paris') } catch { $script:TZ = [System.TimeZoneInfo]::Utc } } $script:RiskOrder = @{ 'Critical' = 1; 'High' = 2; 'Medium' = 3; 'OK' = 4 } $script:SevOrder = @{ 'Critical' = 1; 'High' = 2; 'Medium' = 3; 'Info' = 4; 'Positive' = 5 } $script:Palette = @{ 'Critical' = @{ Fg = '#991b1b'; Bg = '#fee2e2'; Bar = '#dc2626' } 'High' = @{ Fg = '#9a3412'; Bg = '#ffedd5'; Bar = '#ea580c' } 'Medium' = @{ Fg = '#854d0e'; Bg = '#fef9c3'; Bar = '#ca8a04' } 'OK' = @{ Fg = '#166534'; Bg = '#dcfce7'; Bar = '#16a34a' } 'Info' = @{ Fg = '#1e40af'; Bg = '#dbeafe'; Bar = '#2563eb' } 'Positive' = @{ Fg = '#166534'; Bg = '#dcfce7'; Bar = '#16a34a' } } # ============================================================================ # 1. GENERIC HELPERS # ============================================================================ function Write-Log { # Only called at script level (never inside a function that returns a value). param( [Parameter(Mandatory = $true)][string]$Message, [ValidateSet('INFO', 'OK', 'STEP', 'WARN', 'ERROR')][string]$Level = 'INFO' ) $line = '{0} [{1}] {2}' -f (Get-Date).ToUniversalTime().ToString('HH:mm:ss'), $Level.PadRight(5), $Message if ($Level -eq 'WARN') { Write-Warning $line } else { Write-Output $line } } function HE { param($Value) if ($null -eq $Value) { return '' } return [System.Net.WebUtility]::HtmlEncode([string]$Value) } function Num { param($Value) if ($null -eq $Value) { return '0' } return ([double]$Value).ToString('0.#', $script:Invariant) } function ConvertTo-UtcDate { param($Value) if ($null -eq $Value) { return $null } $d = $null if ($Value -is [datetime]) { $d = $Value if ($d.Kind -eq [DateTimeKind]::Local) { $d = $d.ToUniversalTime() } else { $d = [datetime]::SpecifyKind($d, [DateTimeKind]::Utc) } } else { $s = [string]$Value if ([string]::IsNullOrWhiteSpace($s)) { return $null } # No [ref]/TryParse and no enum -bor here: both trigger "Argument types do not match" in PS 5.1 sandboxes $styles = [System.Globalization.DateTimeStyles]'AssumeUniversal, AdjustToUniversal' try { $d = [datetime]::Parse($s, $script:Invariant, $styles) } catch { return $null } } if ($d.Year -lt 1990) { return $null } return $d } function Format-Local { param($UtcDate, [string]$Format = 'yyyy-MM-dd HH:mm') if ($null -eq $UtcDate) { return '' } return [System.TimeZoneInfo]::ConvertTimeFromUtc($UtcDate, $script:TZ).ToString($Format, $script:Invariant) } function Format-Iso { param($UtcDate) if ($null -eq $UtcDate) { return '' } return $UtcDate.ToString('yyyy-MM-ddTHH:mm:ssZ', $script:Invariant) } function Test-SameDate { param($A, $B) $da = ConvertTo-UtcDate $A $db = ConvertTo-UtcDate $B if ($null -eq $da -and $null -eq $db) { return $true } if ($null -eq $da -or $null -eq $db) { return $false } return ([math]::Abs(($da - $db).TotalSeconds) -lt 1) } function Get-Badge { param([string]$Text, [string]$Kind) $p = $script:Palette[$Kind] if (-not $p) { $p = $script:Palette['Info'] } return "$(HE $Text)" } function ConvertTo-CsvBytes { param($Objects, [string]$Delimiter = ';') $delim = [char]$Delimiter.Substring(0, 1) $lines = @($Objects) | ConvertTo-Csv -NoTypeInformation -Delimiter $delim $text = ($lines -join "`r`n") $enc = New-Object System.Text.UTF8Encoding($true) # BOM -> accents OK in Excel $pre = $enc.GetPreamble() $body = $enc.GetBytes($text) $ms = New-Object System.IO.MemoryStream $ms.Write($pre, 0, $pre.Length) $ms.Write($body, 0, $body.Length) return , ($ms.ToArray()) } # ============================================================================ # 2. AUTHENTICATION # ============================================================================ function Get-MsiToken { param([Parameter(Mandatory = $true)][string]$Resource) if (-not $env:IDENTITY_ENDPOINT) { throw "IDENTITY_ENDPOINT not found: enable the managed identity on the Automation Account." } $uri = '{0}?resource={1}&api-version=2019-08-01' -f $env:IDENTITY_ENDPOINT, [uri]::EscapeDataString($Resource) if (-not [string]::IsNullOrWhiteSpace($ManagedIdentityClientId)) { $uri += "&client_id=$ManagedIdentityClientId" } $resp = Invoke-RestMethod -Method Get -Uri $uri -Headers @{ 'X-IDENTITY-HEADER' = $env:IDENTITY_HEADER; 'Metadata' = 'True' } if (-not $resp.access_token) { throw "Managed identity returned no token for $Resource" } return [string]$resp.access_token } function Get-AzLocalToken { param([Parameter(Mandatory = $true)][string]$Resource) if (-not (Get-Module -ListAvailable -Name Az.Accounts)) { throw "Az.Accounts is required locally to reach Azure Storage (Install-Module Az.Accounts -Scope CurrentUser)." } Import-Module Az.Accounts -ErrorAction Stop | Out-Null if (-not (Get-AzContext)) { Connect-AzAccount -ErrorAction Stop | Out-Null } $t = Get-AzAccessToken -ResourceUrl $Resource -ErrorAction Stop if ($t.Token -is [System.Security.SecureString]) { return (New-Object System.Net.NetworkCredential('', $t.Token)).Password } return [string]$t.Token } function Connect-GraphSession { if ($script:IsAzureAutomation) { $script:GraphToken = Get-MsiToken -Resource 'https://graph.microsoft.com' $script:UseMgGraph = $false return } if (-not (Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)) { throw "Microsoft.Graph.Authentication is required locally (Install-Module Microsoft.Graph.Authentication -Scope CurrentUser)." } Import-Module Microsoft.Graph.Authentication -ErrorAction Stop | Out-Null $keyScope = 'BitlockerKey.ReadBasic.All' if ($BackupRecoveryKeys) { $keyScope = 'BitlockerKey.Read.All' } $scopes = @('DeviceManagementManagedDevices.Read.All', $keyScope, 'Device.Read.All', 'Mail.Send') Connect-MgGraph -Scopes $scopes -NoWelcome -ErrorAction Stop | Out-Null $script:UseMgGraph = $true } # ============================================================================ # 3. MICROSOFT GRAPH (throttling aware) # ============================================================================ function Invoke-Graph { param( [Parameter(Mandatory = $true)][string]$Uri, [string]$Method = 'GET', [string]$Body = $null ) $attempt = 0 while ($true) { $attempt++ try { if ($script:UseMgGraph) { $p = @{ Uri = $Uri; Method = $Method; OutputType = 'PSObject'; ErrorAction = 'Stop' } if ($Body) { $p['Body'] = $Body; $p['ContentType'] = 'application/json' } return (Invoke-MgGraphRequest @p) } $h = @{ Authorization = "Bearer $($script:GraphToken)" } $p = @{ Uri = $Uri; Method = $Method; Headers = $h; ErrorAction = 'Stop' } if ($Body) { $p['Body'] = [System.Text.Encoding]::UTF8.GetBytes($Body) $p['ContentType'] = 'application/json; charset=utf-8' } return (Invoke-RestMethod @p) } catch { $err = $_ $status = 0 try { $status = [int]$err.Exception.Response.StatusCode } catch { $status = 0 } $retryAfter = 0 try { $ra = $err.Exception.Response.Headers['Retry-After'] if ($ra) { $retryAfter = [int]$ra } } catch { $retryAfter = 0 } $retryable = ($status -eq 429) -or ($status -ge 500) -or ($status -eq 0 -and $Method -eq 'GET') if ($retryable -and $attempt -lt 6) { $wait = $retryAfter if ($wait -le 0) { $wait = [math]::Min(60, 5 * $attempt) } Write-Warning ("Graph HTTP {0} - retry {1}/5 in {2}s - {3}" -f $status, $attempt, $wait, $Uri) Start-Sleep -Seconds $wait continue } $detail = '' if ($err.ErrorDetails -and $err.ErrorDetails.Message) { $detail = $err.ErrorDetails.Message } throw ("Graph {0} {1} failed (HTTP {2}): {3} {4}" -f $Method, $Uri, $status, $err.Exception.Message, $detail) } } } function Get-GraphAll { param([Parameter(Mandatory = $true)][string]$Uri) $items = New-Object System.Collections.Generic.List[object] $next = $Uri while ($next) { $resp = Invoke-Graph -Uri $next if ($null -ne $resp.value) { foreach ($v in @($resp.value)) { $items.Add($v) } } $next = $resp.'@odata.nextLink' } return , ($items.ToArray()) } # ============================================================================ # 4. STORAGE (Azure Blob via REST + local copy) # ============================================================================ function Get-StorageHeaders { param([hashtable]$Extra) $h = @{ 'Authorization' = "Bearer $($script:StorageToken)" 'x-ms-version' = '2021-08-06' 'x-ms-date' = [DateTime]::UtcNow.ToString('R') } if ($Extra) { foreach ($k in $Extra.Keys) { $h[$k] = $Extra[$k] } } return $h } function Get-BlobUri { param([string]$BlobPath, [string]$Container = '') if ([string]::IsNullOrWhiteSpace($Container)) { $Container = $ContainerName } return "https://$StorageAccountName.blob.core.windows.net/$Container/$BlobPath" } function Get-HttpErrorInfo { param($Err) $status = 0; $code = '' try { $status = [int]$Err.Exception.Response.StatusCode } catch { } try { $code = [string]$Err.Exception.Response.Headers['x-ms-error-code'] } catch { } if (-not $code) { try { $code = [string](@($Err.Exception.Response.Headers.GetValues('x-ms-error-code'))[0]) } catch { } } if (-not $code -and $Err.ErrorDetails -and $Err.ErrorDetails.Message -match '([^<]+)') { $code = $matches[1] } return [pscustomobject]@{ Status = $status; Code = $code; Message = [string]$Err.Exception.Message } } function Get-StorageHint { param($Info, [string]$Container, [string]$Operation) $where = "'$StorageAccountName/$Container' ($Operation)" if ($Info.Status -eq 0 -and $Info.Message -match 'resolve|could not be resolved|No such host|Name or service') { return "Storage account '$StorageAccountName' not found (DNS). Check the exact name (lower case, no space)." } switch ($Info.Code) { 'AuthorizationPermissionMismatch' { return "$where : the managed identity of the Automation Account has no data role. Assign 'Storage Blob Data Contributor' to it on the storage account (IAM), then wait up to 10 minutes." } 'AuthorizationFailure' { return "$where : request blocked by the storage firewall (Networking). Azure Automation cloud jobs are not a trusted service: allow public network access (all networks) or run the runbook on a Hybrid Worker / private endpoint." } 'InvalidAuthenticationInfo' { return "$where : invalid token for Azure Storage (managed identity). $($Info.Message)" } 'KeyBasedAuthenticationNotPermitted' { return "$where : $($Info.Code)." } 'ContainerBeingDeleted' { return "$where : the container is being deleted, retry in a few minutes." } } return ("{0} : HTTP {1} {2} - {3}" -f $where, $Info.Status, $Info.Code, $Info.Message) } function Initialize-StorageContainer { # Returns 'exists' or 'created'; throws a clear, actionable message otherwise. param([string]$Container) $uri = "https://$StorageAccountName.blob.core.windows.net/$Container`?restype=container" try { Invoke-WebRequest -Method Get -Uri $uri -Headers (Get-StorageHeaders) -UseBasicParsing -ErrorAction Stop | Out-Null return 'exists' } catch { $i = Get-HttpErrorInfo $_ if ($i.Status -ne 404) { throw (Get-StorageHint $i $Container 'read') } } try { Invoke-WebRequest -Method Put -Uri $uri -Headers (Get-StorageHeaders) -Body '' -ContentType 'application/octet-stream' -UseBasicParsing -ErrorAction Stop | Out-Null return 'created' } catch { $j = Get-HttpErrorInfo $_ if ($j.Status -eq 409) { return 'exists' } throw ("Container '{0}' does not exist and could not be created - create it in the portal (private). {1}" -f $Container, (Get-StorageHint $j $Container 'create')) } } function Set-BlobContent { param([string]$BlobPath, [byte[]]$Bytes, [string]$ContentType, [string]$Container = '') if ([string]::IsNullOrWhiteSpace($Container)) { $Container = $ContainerName } $h = Get-StorageHeaders -Extra @{ 'x-ms-blob-type' = 'BlockBlob' } try { Invoke-RestMethod -Method Put -Uri (Get-BlobUri -BlobPath $BlobPath -Container $Container) -Headers $h -Body $Bytes -ContentType $ContentType -ErrorAction Stop | Out-Null } catch { $i = Get-HttpErrorInfo $_ throw ("Upload of '{0}' failed: {1}" -f $BlobPath, (Get-StorageHint $i $Container 'write')) } } function Get-BlobText { param([string]$BlobPath) try { $r = Invoke-WebRequest -Method Get -Uri (Get-BlobUri $BlobPath) -Headers (Get-StorageHeaders) -UseBasicParsing -ErrorAction Stop $text = [System.Text.Encoding]::UTF8.GetString($r.RawContentStream.ToArray()) return $text.TrimStart([char]0xFEFF) } catch { $status = 0 try { $status = [int]$_.Exception.Response.StatusCode } catch { } if ($status -eq 404) { return $null } throw ("Read of '{0}/{1}/{2}' failed (HTTP {3}): {4}" -f $StorageAccountName, $ContainerName, $BlobPath, $status, $_.Exception.Message) } } function Save-Artifact { param([string]$RelativePath, [byte[]]$Bytes, [string]$ContentType, [string]$Container = '') $full = $script:LocalStoreDir if (-not [string]::IsNullOrWhiteSpace($Container) -and $Container -ne $ContainerName) { $full = Join-Path $full $Container } foreach ($part in ($RelativePath -split '/')) { $full = Join-Path $full $part } $dir = Split-Path $full -Parent if (-not (Test-Path $dir)) { New-Item -Path $dir -ItemType Directory -Force | Out-Null } [System.IO.File]::WriteAllBytes($full, $Bytes) if ($script:UseBlob) { Set-BlobContent -BlobPath $RelativePath -Bytes $Bytes -ContentType $ContentType -Container $Container } } function Read-PreviousSnapshotText { if ($script:UseBlob) { return (Get-BlobText -BlobPath 'snapshots/latest.json') } $p = Join-Path (Join-Path $script:LocalStoreDir 'snapshots') 'latest.json' if (Test-Path $p) { return [System.IO.File]::ReadAllText($p, [System.Text.Encoding]::UTF8).TrimStart([char]0xFEFF) } return $null } function ConvertFrom-SnapshotJson { param([string]$Text) try { return ($Text | ConvertFrom-Json) } catch { # Windows PowerShell 5.1 fallback for very large snapshots Add-Type -AssemblyName System.Web.Extensions $ser = New-Object System.Web.Script.Serialization.JavaScriptSerializer $ser.MaxJsonLength = [int]::MaxValue return $ser.DeserializeObject($Text) } } # ============================================================================ # 4b. ENCRYPTED KEY BACKUP (public key only - the runbook cannot decrypt) # ============================================================================ function Get-BackupCertificate { $raw = $KeyBackupCertificate if ([string]::IsNullOrWhiteSpace($raw) -and $script:IsAzureAutomation) { try { $raw = Get-AutomationVariable -Name 'BitLockerBackupCert' -ErrorAction Stop } catch { $raw = '' } } if ([string]::IsNullOrWhiteSpace($raw)) { return $null } $bytes = $null if ($raw.Length -lt 260 -and (Test-Path -LiteralPath $raw -PathType Leaf)) { $bytes = [System.IO.File]::ReadAllBytes((Resolve-Path -LiteralPath $raw).Path) $txt = [System.Text.Encoding]::ASCII.GetString($bytes) if ($txt -match '-----BEGIN CERTIFICATE-----' -or $txt -match '^[A-Za-z0-9+/=\s]+$') { $raw = $txt; $bytes = $null } } if ($null -eq $bytes) { $clean = ($raw -replace '-----(BEGIN|END) CERTIFICATE-----', '') -replace '\s', '' $bytes = [Convert]::FromBase64String($clean) } $cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList (, $bytes) if ($cert.HasPrivateKey) { throw 'The backup certificate must contain the PUBLIC key only (.cer). Never store the PFX in Azure.' } return $cert } function Protect-BackupPayload { param([byte[]]$Data, $Cert, [hashtable]$Meta) $aes = [System.Security.Cryptography.Aes]::Create() $aes.KeySize = 256 $aes.Mode = [System.Security.Cryptography.CipherMode]::CBC $aes.Padding = [System.Security.Cryptography.PaddingMode]::PKCS7 $aes.GenerateKey(); $aes.GenerateIV() $iv = $aes.IV $cipher = $aes.CreateEncryptor().TransformFinalBlock($Data, 0, $Data.Length) $macKey = New-Object byte[] 32 [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($macKey) $ivc = New-Object byte[] ($iv.Length + $cipher.Length) [Array]::Copy($iv, 0, $ivc, 0, $iv.Length) [Array]::Copy($cipher, 0, $ivc, $iv.Length, $cipher.Length) $hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList (, $macKey) $tag = $hmac.ComputeHash($ivc) $secret = New-Object byte[] 64 [Array]::Copy($aes.Key, 0, $secret, 0, 32) [Array]::Copy($macKey, 0, $secret, 32, 32) $rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPublicKey($Cert) $pad = 'OAEP-SHA256' try { $wrapped = $rsa.Encrypt($secret, [System.Security.Cryptography.RSAEncryptionPadding]::OaepSHA256) } catch { $wrapped = $rsa.Encrypt($secret, [System.Security.Cryptography.RSAEncryptionPadding]::OaepSHA1); $pad = 'OAEP-SHA1' } [Array]::Clear($secret, 0, $secret.Length); [Array]::Clear($macKey, 0, $macKey.Length) try { $aes.Dispose() } catch { } $envl = [ordered]@{ Format = 'Contoso-BitLockerKeyBackup' FormatVersion = 1 Algorithm = "AES-256-CBC + HMAC-SHA256 (encrypt-then-MAC), key wrapped with RSA $pad" RsaPadding = $pad CertThumbprint = $Cert.Thumbprint CertSubject = $Cert.Subject CertNotAfter = $Cert.NotAfter.ToString('yyyy-MM-dd') } foreach ($k in $Meta.Keys) { $envl[$k] = $Meta[$k] } $envl['WrappedKey'] = [Convert]::ToBase64String($wrapped) $envl['IV'] = [Convert]::ToBase64String($iv) $envl['Hmac'] = [Convert]::ToBase64String($tag) $envl['Ciphertext'] = [Convert]::ToBase64String($cipher) return (New-Object PSObject -Property $envl | ConvertTo-Json -Compress) } function New-DemoRecoveryKey { param($Rnd) $g = @() for ($i = 0; $i -lt 8; $i++) { $g += ('{0:D6}' -f ($Rnd.Next(0, 65536) * 11)) } return ($g -join '-') } # ============================================================================ # 5. ASSESSMENT / SUMMARY / DIFF # ============================================================================ function Get-DeviceAssessment { param([bool]$HasAadId, [bool]$IsEncrypted, [int]$KeyCount, [int]$OsKeyCount) if (-not $HasAadId) { return [pscustomobject]@{ Status = 'No Entra device ID'; Risk = 'High' Recommendation = 'Device not registered in Entra ID: no key can be escrowed. Check the join state (dsregcmd /status) and re-register the device.' } } if ($KeyCount -eq 0 -and $IsEncrypted) { return [pscustomobject]@{ Status = 'Encrypted - NO key in Entra ID'; Risk = 'Critical' Recommendation = 'Escrow now: run BackupToAAD-BitLockerKeyProtector (Intune remediation) or trigger a BitLocker key rotation from Intune.' } } if ($KeyCount -eq 0) { return [pscustomobject]@{ Status = 'Not encrypted - no key'; Risk = 'High' Recommendation = 'Check the BitLocker / Disk encryption policy assignment, TPM readiness and the Intune encryption report.' } } if ($OsKeyCount -eq 0) { return [pscustomobject]@{ Status = 'Key for data volume only'; Risk = 'Medium' Recommendation = 'The OS volume key is missing: run BackupToAAD-BitLockerKeyProtector for C: on the device.' } } if (-not $IsEncrypted) { return [pscustomobject]@{ Status = 'Key escrowed - Intune reports not encrypted'; Risk = 'Medium' Recommendation = 'Check protection status (manage-bde -status): BitLocker may be suspended or the Intune report outdated.' } } return [pscustomobject]@{ Status = 'Protected'; Risk = 'OK'; Recommendation = 'No action.' } } function Get-Summary { param($Records, [string]$GeneratedUtc, [int]$OrphanCount, [int]$TotalKeys) $all = @($Records) $total = $all.Count $withKey = @($all | Where-Object { [int]$_.KeyCount -gt 0 }).Count $cov = 0 if ($total -gt 0) { $cov = [math]::Round(100.0 * $withKey / $total, 1) } return [pscustomobject]@{ GeneratedUtc = $GeneratedUtc TotalDevices = $total WithKey = $withKey WithoutKey = $total - $withKey CoveragePct = $cov Critical = @($all | Where-Object { $_.Risk -eq 'Critical' }).Count High = @($all | Where-Object { $_.Risk -eq 'High' }).Count Medium = @($all | Where-Object { $_.Risk -eq 'Medium' }).Count OK = @($all | Where-Object { $_.Risk -eq 'OK' }).Count Encrypted = @($all | Where-Object { $_.IsEncrypted -eq $true }).Count Stale = @($all | Where-Object { $_.IsStale -eq $true }).Count NoEntraId = @($all | Where-Object { $_.Status -eq 'No Entra device ID' }).Count OrphanKeyDevices = $OrphanCount TotalKeys = $TotalKeys } } function Get-Breakdown { param($Records, $Property, [int]$Top = 10) $rows = @($Records) | Group-Object -Property $Property | ForEach-Object { $tot = $_.Count $wk = @($_.Group | Where-Object { [int]$_.KeyCount -gt 0 }).Count $name = [string]$_.Name if ([string]::IsNullOrWhiteSpace($name)) { $name = '(unknown)' } $cov = 0 if ($tot -gt 0) { $cov = [math]::Round(100.0 * $wk / $tot, 1) } [pscustomobject]@{ Name = $name; Total = $tot; WithKey = $wk; Missing = ($tot - $wk); Coverage = $cov } } return @($rows | Sort-Object -Property @{ Expression = 'Total'; Descending = $true }, @{ Expression = 'Name'; Descending = $false } | Select-Object -First $Top) } function New-Change { param([string]$Severity, [string]$Category, $Device, [string]$Detail) return [pscustomobject]@{ Severity = $Severity Category = $Category DeviceName = [string]$Device.DeviceName SerialNumber = [string]$Device.SerialNumber PrimaryUser = [string]$Device.PrimaryUser HasKey = [string]$Device.HasRecoveryKey CurrentStatus = [string]$Device.Status Detail = $Detail } } function Compare-BitLockerSnapshot { param($Previous, $Current, [int]$StaleThreshold) $changes = New-Object System.Collections.Generic.List[object] $prevMap = @{} foreach ($p in @($Previous)) { if ($p.IntuneDeviceId) { $prevMap[[string]$p.IntuneDeviceId] = $p } } $curMap = @{} foreach ($c in @($Current)) { $curMap[[string]$c.IntuneDeviceId] = $c } $newList = New-Object System.Collections.Generic.List[object] $removedList = New-Object System.Collections.Generic.List[object] foreach ($c in @($Current)) { $id = [string]$c.IntuneDeviceId if (-not $prevMap.ContainsKey($id)) { $newList.Add($c); continue } $p = $prevMap[$id] $before = $changes.Count $pk = [int]$p.KeyCount $ck = [int]$c.KeyCount if ($pk -gt 0 -and $ck -eq 0) { $changes.Add((New-Change 'Critical' 'Recovery key lost' $c ("Had {0} key(s) (last backup {1}) - none found in Entra ID now" -f $pk, $p.LastKeyBackup))) } elseif ($pk -eq 0 -and $ck -gt 0) { $changes.Add((New-Change 'Positive' 'Recovery key escrowed' $c ("Key backed up on {0}" -f $c.LastKeyBackup))) } elseif ($ck -gt 0 -and -not (Test-SameDate $p.LastKeyBackupUtc $c.LastKeyBackupUtc)) { $changes.Add((New-Change 'Info' 'Key rotated / new key' $c ("Last backup {0} -> {1} ({2} key(s))" -f $p.LastKeyBackup, $c.LastKeyBackup, $ck))) } $pe = ($p.IsEncrypted -eq $true) $ce = ($c.IsEncrypted -eq $true) if ($pe -and -not $ce) { $changes.Add((New-Change 'High' 'Encryption disabled' $c 'Intune now reports the device as NOT encrypted')) } elseif (-not $pe -and $ce) { $changes.Add((New-Change 'Positive' 'Encryption enabled' $c 'Intune now reports the device as encrypted')) } if (-not ($p.IsStale -eq $true) -and ($c.IsStale -eq $true)) { $changes.Add((New-Change 'Medium' 'Stopped syncing' $c ("No Intune sync for {0} days (last sync {1}) - leaving production?" -f $c.DaysSinceSync, $c.LastSync))) } if ([string]$p.ComplianceState -ne [string]$c.ComplianceState) { $sev = 'Info' if ([string]$c.ComplianceState -eq 'noncompliant') { $sev = 'Medium' } $changes.Add((New-Change $sev 'Compliance changed' $c ("{0} -> {1}" -f $p.ComplianceState, $c.ComplianceState))) } if ([string]$p.DeviceName -ne [string]$c.DeviceName) { $changes.Add((New-Change 'Info' 'Renamed' $c ("{0} -> {1}" -f $p.DeviceName, $c.DeviceName))) } if ($changes.Count -eq $before -and [string]$p.Risk -ne [string]$c.Risk) { $po = $script:RiskOrder[[string]$p.Risk]; $co = $script:RiskOrder[[string]$c.Risk] $sev = 'Positive' if ($co -lt $po) { $sev = [string]$c.Risk } $changes.Add((New-Change $sev 'Risk level changed' $c ("{0} -> {1} ({2})" -f $p.Risk, $c.Risk, $c.Status))) } } foreach ($p in @($Previous)) { if (-not $curMap.ContainsKey([string]$p.IntuneDeviceId)) { $removedList.Add($p) } } # Re-enrolment detection (same serial number, new Intune ID) $junkSerial = '^(0+|to be filled.|default string|system serial number|none|n/a)$' $removedBySerial = @{} foreach ($r in $removedList) { $s = [string]$r.SerialNumber if ($s -and $s -notmatch $junkSerial) { $removedBySerial[$s] = $r } } $matched = @{} foreach ($n in $newList) { $s = [string]$n.SerialNumber $sev = 'Info' if ($n.Risk -ne 'OK') { $sev = [string]$n.Risk } if ($s -and $removedBySerial.ContainsKey($s) -and -not $matched.ContainsKey($s)) { $matched[$s] = $true $changes.Add((New-Change $sev 'Re-enrolled' $n ("Same serial re-enrolled (was '{0}') - key escrowed: {1} - {2}" -f $removedBySerial[$s].DeviceName, $n.HasRecoveryKey, $n.Status))) continue } $changes.Add((New-Change $sev 'New device' $n ("Enrolled {0} - key escrowed: {1} - {2}" -f $n.Enrolled, $n.HasRecoveryKey, $n.Status))) } foreach ($r in $removedList) { $s = [string]$r.SerialNumber if ($s -and $matched.ContainsKey($s)) { continue } $changes.Add((New-Change 'Info' 'Device removed' $r ("No longer in Intune (last sync {0}, key escrowed: {1})" -f $r.LastSync, $r.HasRecoveryKey))) } $sorted = @($changes | Sort-Object -Property @{ Expression = { $script:SevOrder[$_.Severity] } }, Category, DeviceName) $stats = [pscustomobject]@{ Total = $sorted.Count NewDevices = @($sorted | Where-Object { $_.Category -eq 'New device' }).Count Removed = @($sorted | Where-Object { $_.Category -eq 'Device removed' }).Count ReEnrolled = @($sorted | Where-Object { $_.Category -eq 'Re-enrolled' }).Count KeysLost = @($sorted | Where-Object { $_.Category -eq 'Recovery key lost' }).Count KeysEscrowed = @($sorted | Where-Object { $_.Category -eq 'Recovery key escrowed' }).Count KeysRotated = @($sorted | Where-Object { $_.Category -eq 'Key rotated / new key' }).Count EncryptionOff = @($sorted | Where-Object { $_.Category -eq 'Encryption disabled' }).Count BecameStale = @($sorted | Where-Object { $_.Category -eq 'Stopped syncing' }).Count NewWithoutKey = @($sorted | Where-Object { ($_.Category -eq 'New device' -or $_.Category -eq 'Re-enrolled') -and $_.HasKey -eq 'No' }).Count } return [pscustomobject]@{ Changes = $sorted; Stats = $stats } } # ============================================================================ # 6. DEMO DATA (offline preview) # ============================================================================ function New-DemoData { $rnd = New-Object System.Random 42 $hw = @( @('Dell Inc.', 'Latitude 5440'), @('Dell Inc.', 'Latitude 7440'), @('HP', 'EliteBook 840 G10'), @('HP', 'ZBook Firefly 14 G10'), @('LENOVO', 'ThinkPad T14 Gen 4'), @('Microsoft Corporation', 'Surface Laptop 5') ) $builds = @('10.0.26100.2314', '10.0.22631.4460', '10.0.22631.4317', '10.0.19045.5131') $joins = @('azureADJoined', 'azureADJoined', 'azureADJoined', 'hybridAzureADJoined') $now = (Get-Date).ToUniversalTime() $devices = New-Object System.Collections.Generic.List[object] $keys = New-Object System.Collections.Generic.List[object] $entra = New-Object System.Collections.Generic.List[object] for ($i = 1; $i -le 120; $i++) { $m = $hw[$rnd.Next($hw.Count)] $aad = [guid]::NewGuid().ToString() $roll = $rnd.Next(100) if ($i -eq 7 -or $i -eq 63) { $aad = '00000000-0000-0000-0000-000000000000' } $enc = ($roll -ge 5) $compliance = 'compliant' if ($rnd.Next(12) -eq 0) { $compliance = 'noncompliant' } $syncAge = $rnd.Next(1, 24 * 20) if ($rnd.Next(15) -eq 0) { $syncAge = $rnd.Next(24 * 35, 24 * 90) } $devices.Add([pscustomobject]@{ id = [guid]::NewGuid().ToString() deviceName = ('CONTOSO-PC-{0:D4}' -f (1000 + $i)) serialNumber = ('SN{0:D7}' -f (4500000 + $i * 37)) model = $m[1] manufacturer = $m[0] osVersion = $builds[$rnd.Next($builds.Count)] azureADDeviceId = $aad complianceState = $compliance isEncrypted = $enc lastSyncDateTime = $now.AddHours(-$syncAge).ToString('o') enrolledDateTime = $now.AddDays(-$rnd.Next(5, 700)).ToString('o') userPrincipalName = ('user{0:D3}@contoso.com' -f $i) managementAgent = 'mdm' joinType = $joins[$rnd.Next($joins.Count)] managedDeviceOwnerType = 'company' }) if ($aad -ne '00000000-0000-0000-0000-000000000000') { $entra.Add([pscustomobject]@{ deviceId = $aad; displayName = ('CONTOSO-PC-{0:D4}' -f (1000 + $i)); accountEnabled = $true; trustType = 'AzureAd' }) $hasKey = ($roll -ge 9) -or ($roll -lt 5 -and $rnd.Next(2) -eq 0) if ($hasKey) { $vt = 'operatingSystemVolume' if ($i % 41 -eq 0) { $vt = 'fixedDataVolume' } $keys.Add([pscustomobject]@{ id = [guid]::NewGuid().ToString(); deviceId = $aad; volumeType = $vt; createdDateTime = $now.AddDays(-$rnd.Next(1, 400)).ToString('o') }) if ($rnd.Next(6) -eq 0) { $keys.Add([pscustomobject]@{ id = [guid]::NewGuid().ToString(); deviceId = $aad; volumeType = 'fixedDataVolume'; createdDateTime = $now.AddDays(-$rnd.Next(1, 400)).ToString('o') }) } } } } for ($j = 1; $j -le 4; $j++) { $oid = [guid]::NewGuid().ToString() $keys.Add([pscustomobject]@{ id = [guid]::NewGuid().ToString(); deviceId = $oid; volumeType = 'operatingSystemVolume'; createdDateTime = $now.AddDays(-$rnd.Next(100, 600)).ToString('o') }) if ($j -le 2) { $entra.Add([pscustomobject]@{ deviceId = $oid; displayName = ('CONTOSO-OLD-{0:D3}' -f $j); accountEnabled = $false; trustType = 'AzureAd' }) } } return @{ Devices = $devices.ToArray(); Keys = $keys.ToArray(); Entra = $entra.ToArray() } } function New-DemoPrevious { param($Records) $all = @($Records) $prev = New-Object System.Collections.Generic.List[object] for ($i = 6; $i -lt $all.Count; $i++) { $prev.Add($all[$i].PSObject.Copy()) } # first 6 devices = "new" $okPick = @($prev | Where-Object { $_.Risk -eq 'OK' } | Select-Object -First 3) $crit = $prev | Where-Object { $_.Risk -eq 'Critical' } | Select-Object -First 1 foreach ($o in $okPick) { $o.KeyCount = 0; $o.OsVolumeKeyCount = 0; $o.HasRecoveryKey = 'No'; $o.Risk = 'Critical'; $o.Status = 'Encrypted - NO key in Entra ID' $o.LastKeyBackup = ''; $o.LastKeyBackupUtc = '' } if ($crit) { $crit.KeyCount = 1; $crit.OsVolumeKeyCount = 1; $crit.HasRecoveryKey = 'Yes'; $crit.Risk = 'OK'; $crit.Status = 'Protected' $crit.LastKeyBackup = '2026-03-02 09:14'; $crit.LastKeyBackupUtc = '2026-03-02T08:14:00Z' } foreach ($o in @($prev | Where-Object { $_.IsStale -eq $true } | Select-Object -First 2)) { $o.IsStale = $false } $tpl = $all[$all.Count - 1] for ($i = 1; $i -le 4; $i++) { $x = $tpl.PSObject.Copy() $x.IntuneDeviceId = [guid]::NewGuid().ToString(); $x.DeviceName = ('CONTOSO-LT-{0:D3}' -f (900 + $i)); $x.SerialNumber = ('OLD{0:D6}' -f $i) $x.LastSync = '2026-09-28 17:40' $prev.Add($x) } $genUtc = Format-Iso ((Get-Date).ToUniversalTime().AddDays(-31)) return [pscustomobject]@{ GeneratedUtc = $genUtc Summary = (Get-Summary -Records $prev.ToArray() -GeneratedUtc $genUtc -OrphanCount 3 -TotalKeys 101) Devices = $prev.ToArray() } } # ============================================================================ # 7. E-MAIL HTML (Outlook-safe: tables + inline styles only) # ============================================================================ function Get-DeltaHtml { param($Current, $Previous, [string]$Suffix = '', [bool]$HigherIsBetter = $true, [bool]$Neutral = $false) if ($null -eq $Previous) { return ' ' } $d = [double]$Current - [double]$Previous if ([math]::Abs($d) -lt 0.05) { return "= vs last run" } $sign = '' if ($d -gt 0) { $sign = '+' } $col = '#64748b' if (-not $Neutral) { if (($d -gt 0) -eq $HigherIsBetter) { $col = '#16a34a' } else { $col = '#dc2626' } } return "$sign$(Num $d)$Suffix vs last run" } function Get-EmailKpi { param([string]$Value, [string]$Label, [string]$Color, [string]$Sub, [bool]$Last = $false) $border = 'border-right:1px solid #f1f5f9;' if ($Last) { $border = '' } return "
$Value
$Label
$Sub
" } function Get-EmailCard { param([string]$Title, [string]$Subtitle, [string]$Inner) $sub = '' if ($Subtitle) { $sub = "
$Subtitle
" } return "
$Title$sub
$Inner
" } function Get-EmailTableHead { param([string[]]$Headers) $h = "" foreach ($x in $Headers) { $h += "" } return $h + '' } function New-EmailHtml { param($Summary, $Previous, $Diff, $Records, $Orphans, [hashtable]$Ctx) $F = $script:F $td = "padding:8px;border-bottom:1px solid #f1f5f9;font-size:12px;color:#334155;vertical-align:top;" $prevSum = $null if ($Previous) { $prevSum = $Previous.Summary } $sb = New-Object System.Text.StringBuilder $modeLine = "Initial baseline · generated $(HE $Ctx.GeneratedLocal) (Paris time)" if (-not $Ctx.IsBaseline) { $modeLine = "Report $(HE $Ctx.Period) · changes since $(HE $Ctx.PrevLocal) · generated $(HE $Ctx.GeneratedLocal)" } if ($Ctx.Demo) { $modeLine = "DEMO DATA · $modeLine" } [void]$sb.Append("") [void]$sb.Append("
$x
" } $tbl += '
") [void]$sb.Append("") # Header [void]$sb.Append("") # KPIs $pS = $null; if ($prevSum) { $pS = $prevSum } $dTot = ' '; $dWith = ' '; $dMiss = ' '; $dCov = ' ' if ($pS) { $dTot = Get-DeltaHtml $Summary.TotalDevices $pS.TotalDevices '' $true $true $dWith = Get-DeltaHtml $Summary.WithKey $pS.WithKey '' $true $dMiss = Get-DeltaHtml $Summary.WithoutKey $pS.WithoutKey '' $false $dCov = Get-DeltaHtml $Summary.CoveragePct $pS.CoveragePct ' pts' $true } $missColor = '#16a34a'; if ($Summary.WithoutKey -gt 0) { $missColor = '#dc2626' } $covColor = '#16a34a'; if ($Summary.CoveragePct -lt 98) { $covColor = '#ca8a04' }; if ($Summary.CoveragePct -lt 90) { $covColor = '#dc2626' } [void]$sb.Append("") # Banner $bBg = '#dcfce7'; $bFg = '#166534'; $bBar = '#16a34a' $bText = "✅ All $($Summary.TotalDevices) Windows devices have a BitLocker recovery key escrowed in Entra ID." if ($Summary.WithoutKey -gt 0) { $bBg = '#ffedd5'; $bFg = '#9a3412'; $bBar = '#ea580c' $bText = "⚠️ $($Summary.WithoutKey) device(s) have no recovery key in Entra ID (not encrypted or not registered)." } if ($Summary.Critical -gt 0) { $bBg = '#fee2e2'; $bFg = '#991b1b'; $bBar = '#dc2626' $bText = "🚨 $($Summary.Critical) ENCRYPTED device(s) have NO recovery key in Entra ID: a BitLocker recovery prompt on these machines means data loss. Action required." } if ($Diff -and $Diff.Stats.KeysLost -gt 0) { $bText += "
❌ $($Diff.Stats.KeysLost) device(s) LOST their escrowed key since the last run." } if ($Ctx.Suspicious) { $bBg = '#fee2e2'; $bFg = '#991b1b'; $bBar = '#dc2626' $bText = "🚨 Device count dropped from $($prevSum.TotalDevices) to $($Summary.TotalDevices) (more than 50 %). Possible partial Graph result: the reference snapshot was NOT updated. " + $bText } [void]$sb.Append("") # Coverage bar $pct = [double]$Summary.CoveragePct $w = [int][math]::Round($pct) if ($w -lt 1) { $w = 1 } if ($w -gt 99 -and $pct -lt 100) { $w = 99 } $barCells = "" if ($w -lt 100) { $barCells += "" } $riskLine = "$(Get-Badge "Critical $($Summary.Critical)" 'Critical')   $(Get-Badge "High $($Summary.High)" 'High')   $(Get-Badge "Medium $($Summary.Medium)" 'Medium')   $(Get-Badge "Protected $($Summary.OK)" 'OK')" $extra = "Encrypted (Intune): $($Summary.Encrypted) · Not synced for > $($Ctx.StaleDays) days: $($Summary.Stale) · Recovery keys in tenant: $($Summary.TotalKeys)" [void]$sb.Append("") # Changes / baseline if ($Ctx.IsBaseline) { $inner = "
This is the first snapshot: it becomes the reference. From the next run, this e-mail lists what changed: new devices (with or without key), devices leaving production, re-enrolments, keys lost / escrowed / rotated, encryption changes and devices that stopped syncing.
" [void]$sb.Append((Get-EmailCard '📌 Baseline created' "Snapshot archived in $(HE $Ctx.Storage)" $inner)) } else { $st = $Diff.Stats $chips = @( @('New devices', $st.NewDevices, '#2563eb'), @('Removed', $st.Removed, '#64748b'), @('Re-enrolled', $st.ReEnrolled, '#7c3aed'), @('New w/o key', $st.NewWithoutKey, '#dc2626'), @('Keys lost', $st.KeysLost, '#dc2626'), @('Keys escrowed', $st.KeysEscrowed, '#16a34a'), @('Stopped syncing', $st.BecameStale, '#ca8a04') ) $chipHtml = "
") [void]$sb.Append("
$(HE $Ctx.Tenant) · Intune & Entra ID
") [void]$sb.Append("
🔐 BitLocker Recovery Key Report
") [void]$sb.Append("
$modeLine
") [void]$sb.Append((Get-EmailKpi "$($Summary.TotalDevices)" 'Windows devices' '#0f172a' $dTot)) [void]$sb.Append((Get-EmailKpi "$($Summary.WithKey)" 'Key escrowed' '#16a34a' $dWith)) [void]$sb.Append((Get-EmailKpi "$($Summary.WithoutKey)" 'Missing key' $missColor $dMiss)) [void]$sb.Append((Get-EmailKpi "$(Num $Summary.CoveragePct)%" 'Coverage' $covColor $dCov $true)) [void]$sb.Append("
$bText
  
KEY ESCROW COVERAGE
$barCells
$riskLine
$extra
" foreach ($c in $chips) { $col = '#94a3b8'; if ([int]$c[1] -gt 0) { $col = $c[2] } $chipHtml += "" } $chipHtml += "
$($c[1])
$($c[0])
" $tbl = '' if ($st.Total -gt 0) { $tbl = "
 
" + (Get-EmailTableHead @('Severity', 'Change', 'Device', 'Detail')) foreach ($ch in @($Diff.Changes | Select-Object -First $Ctx.MaxRows)) { $tbl += "
$(Get-Badge $ch.Severity $ch.Severity)$(HE $ch.Category)$(HE $ch.DeviceName)
$(HE $ch.PrimaryUser)
$(HE $ch.Detail)
' if ($st.Total -gt $Ctx.MaxRows) { $tbl += "
+ $($st.Total - $Ctx.MaxRows) more change(s) in the attached report / CSV.
" } } else { $tbl = "
No change detected since the previous snapshot.
" } [void]$sb.Append((Get-EmailCard '🔄 What changed since the last snapshot' "$($st.Total) change(s) since $(HE $Ctx.PrevLocal)" ($chipHtml + $tbl))) } # Action required $atRisk = @($Records | Where-Object { $_.Risk -ne 'OK' } | Sort-Object -Property @{ Expression = { $script:RiskOrder[$_.Risk] } }, DeviceName) if ($atRisk.Count -gt 0) { $tbl = Get-EmailTableHead @('Risk', 'Device', 'User', 'Status / action', 'Last sync') foreach ($d in @($atRisk | Select-Object -First $Ctx.MaxRows)) { $sync = HE $d.LastSync if ($d.IsStale -eq $true) { $sync = "$sync" } $tbl += "$(Get-Badge $d.Risk $d.Risk)$(HE $d.DeviceName)
$(HE $d.SerialNumber)$(HE $d.PrimaryUser)$(HE $d.Status)
$(HE $d.Recommendation)$sync" } $tbl += '' if ($atRisk.Count -gt $Ctx.MaxRows) { $tbl += "
+ $($atRisk.Count - $Ctx.MaxRows) more device(s) in the attached report / CSV.
" } [void]$sb.Append((Get-EmailCard '🔧 Devices requiring action' "$($atRisk.Count) device(s) - sorted by risk" $tbl)) } # Manufacturer breakdown $rows = Get-Breakdown -Records $Records -Property 'Manufacturer' -Top 8 $tbl = Get-EmailTableHead @('Manufacturer', 'Devices', 'Missing key', 'Coverage') foreach ($r in $rows) { $col = '#16a34a'; if ($r.Coverage -lt 98) { $col = '#ca8a04' }; if ($r.Coverage -lt 90) { $col = '#dc2626' } $miss = "0"; if ($r.Missing -gt 0) { $miss = "$($r.Missing)" } $tbl += "$(HE $r.Name)$($r.Total)$miss$(Num $r.Coverage)%" } $tbl += '' [void]$sb.Append((Get-EmailCard '💻 Coverage by manufacturer' '' $tbl)) # Orphans + attachments $foot = '' if (@($Orphans).Count -gt 0) { $foot += "
🔑 $(@($Orphans).Count) device(s) still hold recovery keys in Entra ID but are no longer managed by Intune (out of production / to clean up) - see the full report.
" } $foot += "
📎 Attachments: $(HE $Ctx.AttachmentList)
" if ($Ctx.AttachmentNote) { $foot += "
$(HE $Ctx.AttachmentNote)
" } $foot += "
💾 Archive: $(HE $Ctx.Storage)
" $bk = $Ctx.Backup if ($bk -and $bk.Enabled) { $kind = 'OK'; $title = '🔒 Recovery key backup (encrypted)' $txt = "$($bk.Exported) recovery key(s) exported and encrypted with the offline certificate (thumbprint $(HE $bk.Thumbprint)).
Location: $(HE $bk.Location)" if ($bk.Status -eq 'Partial') { $kind = 'High'; $txt += "
$($bk.Failed) key(s) could not be read - check the job output." } elseif ($bk.Status -eq 'Not stored') { $kind = 'High'; $txt += "
No StorageAccountName: the backup file was NOT kept." } elseif ($bk.Status -ne 'OK') { $kind = 'Critical'; $txt = "Backup $(HE $bk.Status): $(HE $bk.Error)" } if ($bk.CertWarning) { $txt += "
$(HE $bk.CertWarning)" } $txt += "
Key values never appear in this e-mail. Decrypt offline with Restore-BitLockerKeys.ps1 and the PFX." [void]$sb.Append((Get-EmailCard $title '' ("$(Get-Badge $bk.Status $kind)
$txt
"))) } [void]$sb.Append((Get-EmailCard 'ℹ️ Details' '' $foot)) [void]$sb.Append("BitLocker Key Escrow Monitor v$($Ctx.Version) · $(HE $Ctx.RunEnv) · recovery key values are never read nor exported") [void]$sb.Append("") return $sb.ToString() } function New-FailureHtml { param([string]$Message) return "
BitLocker Key Escrow Monitor - run FAILED
The reference snapshot was not updated. Error:
$(HE $Message)
" } # ============================================================================ # 8. FULL HTML REPORT (standalone file: search, filters, sortable tables) # ============================================================================ function Get-BreakdownCardHtml { param([string]$Title, [string]$Subtitle, $Rows, [string]$NameHeader = 'Name') $sb = New-Object System.Text.StringBuilder [void]$sb.Append("

$(HE $Title)

$(HE $Subtitle)
") foreach ($r in @($Rows)) { $col = '#16a34a'; if ($r.Coverage -lt 98) { $col = '#ca8a04' }; if ($r.Coverage -lt 90) { $col = '#dc2626' } $miss = "0"; if ($r.Missing -gt 0) { $miss = "$($r.Missing)" } [void]$sb.Append("") } [void]$sb.Append('
$(HE $NameHeader)DevicesMissingCoverage
$(HE $r.Name)$($r.Total)$miss
$(Num $r.Coverage)%
') return $sb.ToString() } function New-FullHtmlReport { param($Summary, $Previous, $Diff, $Records, $Orphans, [hashtable]$Ctx) $css = @' :root{--bg:#f1f5f9;--card:#fff;--ink:#0f172a;--muted:#64748b;--line:#e2e8f0} *{box-sizing:border-box} body{margin:0;background:var(--bg);font-family:'Segoe UI',system-ui,-apple-system,Arial,sans-serif;color:var(--ink);font-size:14px} .hero{background:linear-gradient(135deg,#0f172a 0%,#1e3a8a 55%,#2563eb 100%);color:#fff;padding:36px 48px 74px} .hero .eyebrow{font-size:12px;letter-spacing:1.4px;text-transform:uppercase;color:#93c5fd;font-weight:700} .hero h1{margin:6px 0 0;font-size:30px;font-weight:700;letter-spacing:-.5px} .hero p{margin:8px 0 0;color:#bfdbfe} .chips{margin-top:18px;display:flex;flex-wrap:wrap;gap:8px} .chip{background:rgba(255,255,255,.12);border:1px solid rgba(255,255,255,.22);padding:5px 12px;border-radius:999px;font-size:12px} .wrap{max-width:1320px;margin:-46px auto 40px;padding:0 24px} .kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(165px,1fr));gap:14px} .kpi{background:var(--card);border-radius:12px;padding:18px;box-shadow:0 1px 3px rgba(15,23,42,.08);border-top:4px solid var(--c)} .kpi .v{font-size:30px;font-weight:700;color:var(--c)} .kpi .l{font-size:11px;text-transform:uppercase;letter-spacing:.6px;color:var(--muted);font-weight:700;margin-top:4px} .kpi .s{font-size:12px;margin-top:6px;color:var(--muted)} .card{background:var(--card);border-radius:12px;box-shadow:0 1px 3px rgba(15,23,42,.08);padding:20px 22px;margin-top:18px} .card h2{margin:0 0 4px;font-size:17px} .card .sub{color:var(--muted);font-size:12px;margin-bottom:14px} .grid2{display:grid;grid-template-columns:repeat(auto-fit,minmax(400px,1fr));gap:0 18px} .gaugebox{display:flex;align-items:center;gap:30px;flex-wrap:wrap} .gauge{width:180px;height:180px;border-radius:50%;background:conic-gradient(#16a34a calc(var(--p) * 1%),#fecaca 0);display:flex;align-items:center;justify-content:center;flex:none} .gauge div{width:132px;height:132px;border-radius:50%;background:#fff;display:flex;flex-direction:column;align-items:center;justify-content:center} .gauge b{font-size:32px} .gauge span{font-size:11px;color:var(--muted);text-transform:uppercase;letter-spacing:.6px} .facts div{padding:5px 0;border-bottom:1px dashed var(--line);font-size:13px} .facts b{display:inline-block;min-width:54px} .riskrow{display:flex;align-items:center;gap:10px;margin:10px 0} .riskrow .lbl{width:150px;font-size:13px} .riskrow .n{width:60px;text-align:right;font-weight:700} .bar{height:10px;background:#f1f5f9;border-radius:999px;overflow:hidden;flex:1} .bar i{display:block;height:100%;border-radius:999px} .cov{display:flex;align-items:center;gap:8px} .cov span{font-size:12px;min-width:46px;text-align:right} table.t{width:100%;border-collapse:collapse;font-size:13px} table.t th{background:#f8fafc;color:#475569;text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.4px;padding:9px 10px;border-bottom:1px solid var(--line);position:sticky;top:0;white-space:nowrap;z-index:1} table.sortable th{cursor:pointer} table.sortable th:hover{color:#1e3a8a} table.t td{padding:8px 10px;border-bottom:1px solid #f1f5f9;vertical-align:top} table.t tr:hover td{background:#f8fafc} .r{text-align:right!important} .badge{display:inline-block;padding:2px 9px;border-radius:999px;font-size:11px;font-weight:700;white-space:nowrap} .mono{font-family:Consolas,'Cascadia Mono',monospace;font-size:12px;color:#475569} .muted{color:var(--muted)} .small{font-size:11px;color:var(--muted)} .scroll{max-height:640px;overflow:auto;border:1px solid var(--line);border-radius:10px} .toolbar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:12px} .toolbar input{flex:1;min-width:240px;padding:9px 12px;border:1px solid var(--line);border-radius:8px;font-size:13px} .flt{border:1px solid var(--line);background:#fff;padding:7px 12px;border-radius:8px;cursor:pointer;font-size:12px;font-weight:700;color:#334155} .flt.on{background:#1e3a8a;color:#fff;border-color:#1e3a8a} .banner{border-radius:12px;padding:14px 18px;margin-top:18px;font-weight:600;border-left:6px solid} .stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:16px} .stat{background:#f8fafc;border:1px solid var(--line);border-radius:10px;padding:10px 12px} .stat b{display:block;font-size:22px} .stat span{font-size:10px;color:var(--muted);text-transform:uppercase;font-weight:700;letter-spacing:.4px} footer{text-align:center;color:#94a3b8;font-size:12px;margin:30px 0} @media print{.hero,.gauge,.bar i,.badge{-webkit-print-color-adjust:exact;print-color-adjust:exact}.scroll{max-height:none;overflow:visible}.toolbar{display:none}} '@ $js = @' (function(){ var q=document.getElementById('q'), cnt=document.getElementById('cnt'), rf='All'; function apply(){ if(!q){return;} var t=q.value.toLowerCase(), rows=document.querySelectorAll('#inv tbody tr'), n=0; for(var i=0;i-1)&&(rf==='All'||r.getAttribute('data-risk')===rf||(rf==='Stale'&&r.getAttribute('data-stale')==='1')); r.style.display=ok?'':'none'; if(ok){n++;} } if(cnt){cnt.textContent=n;} } if(q){q.addEventListener('input',apply);} var b=document.querySelectorAll('.flt'); for(var i=0;iBitLocker Recovery Key Report - $(HE $Ctx.Tenant) - $(HE $Ctx.GeneratedLocal)") # HERO $mode = 'Initial baseline' if (-not $Ctx.IsBaseline) { $mode = "Delta since $($Ctx.PrevLocal)" } if ($Ctx.Demo) { $mode = "DEMO DATA - $mode" } [void]$sb.Append("
$(HE $Ctx.Tenant) · Intune & Entra ID

🔐 BitLocker Recovery Key Report

Escrow status of BitLocker recovery keys for every Windows device managed by Intune - $(HE $Ctx.Period)

") [void]$sb.Append("Generated $(HE $Ctx.GeneratedLocal) (Paris)$(HE $mode)Stale threshold: $($Ctx.StaleDays) daysArchive: $(HE $Ctx.Storage)v$($Ctx.Version)
") # KPIs $kp = @( @("$($Summary.TotalDevices)", 'Windows devices', '#0f172a', $(if ($prevSum) { Get-DeltaHtml $Summary.TotalDevices $prevSum.TotalDevices '' $true $true } else { ' ' })), @("$($Summary.WithKey)", 'Key escrowed', '#16a34a', $(if ($prevSum) { Get-DeltaHtml $Summary.WithKey $prevSum.WithKey '' $true } else { ' ' })), @("$($Summary.WithoutKey)", 'Missing key', $(if ($Summary.WithoutKey -gt 0) { '#dc2626' } else { '#16a34a' }), $(if ($prevSum) { Get-DeltaHtml $Summary.WithoutKey $prevSum.WithoutKey '' $false } else { ' ' })), @("$(Num $Summary.CoveragePct)%", 'Coverage', $(if ($Summary.CoveragePct -ge 98) { '#16a34a' } elseif ($Summary.CoveragePct -ge 90) { '#ca8a04' } else { '#dc2626' }), $(if ($prevSum) { Get-DeltaHtml $Summary.CoveragePct $prevSum.CoveragePct ' pts' $true } else { ' ' })), @("$($Summary.Critical)", 'Critical', '#dc2626', 'Encrypted, no key'), @("$($Summary.Stale)", 'Stale devices', '#ca8a04', "No sync > $($Ctx.StaleDays) days"), @("$($Summary.OrphanKeyDevices)", 'Orphan keys', '#7c3aed', 'Keys of unmanaged devices') ) [void]$sb.Append("
") foreach ($k in $kp) { [void]$sb.Append("
$($k[0])
$($k[1])
$($k[3])
") } [void]$sb.Append("
") # Banner $bBg = '#dcfce7'; $bFg = '#166534'; $bBar = '#16a34a' $bText = "✅ All $($Summary.TotalDevices) Windows devices have a BitLocker recovery key escrowed in Entra ID." if ($Summary.WithoutKey -gt 0) { $bBg = '#ffedd5'; $bFg = '#9a3412'; $bBar = '#ea580c'; $bText = "⚠️ $($Summary.WithoutKey) device(s) have no recovery key in Entra ID." } if ($Summary.Critical -gt 0) { $bBg = '#fee2e2'; $bFg = '#991b1b'; $bBar = '#dc2626'; $bText = "🚨 $($Summary.Critical) ENCRYPTED device(s) have NO recovery key in Entra ID - a recovery prompt on these machines means data loss." } if ($Ctx.Suspicious) { $bBg = '#fee2e2'; $bFg = '#991b1b'; $bBar = '#dc2626'; $bText = "🚨 Device count dropped by more than 50 % - possible partial data: the reference snapshot was NOT updated. " + $bText } [void]$sb.Append("") # Gauge + risk distribution $tot = [math]::Max(1, [int]$Summary.TotalDevices) [void]$sb.Append("

Key escrow coverage

Devices with at least one recovery key stored in Entra ID
$(Num $Summary.CoveragePct)%covered
") [void]$sb.Append("
$($Summary.WithKey) devices with a key
$($Summary.WithoutKey) devices without key
$($Summary.Encrypted) encrypted (Intune report)
$($Summary.NoEntraId) without Entra device ID
$($Summary.TotalKeys) recovery keys in the tenant
") [void]$sb.Append("

Risk distribution

Classification of each device (see legend at the bottom)
") foreach ($rk in @('Critical', 'High', 'Medium', 'OK')) { $n = [int]$Summary.$rk $lbl = $rk; if ($rk -eq 'OK') { $lbl = 'Protected' } [void]$sb.Append("
$(Get-Badge $lbl $rk)
$n
") } [void]$sb.Append("
") # Changes if ($Ctx.IsBaseline) { [void]$sb.Append("

📌 Baseline created

No previous snapshot

This report is the reference. Each next run compares the inventory with this snapshot and reports new devices, devices leaving production, re-enrolments, recovery keys lost / escrowed / rotated, encryption and compliance changes and devices that stopped syncing.

") } else { $st = $Diff.Stats [void]$sb.Append("

🔄 Changes since the last snapshot

$($st.Total) change(s) between $(HE $Ctx.PrevLocal) and $(HE $Ctx.GeneratedLocal)
") $stItems = @(@('New devices', $st.NewDevices), @('Removed', $st.Removed), @('Re-enrolled', $st.ReEnrolled), @('New without key', $st.NewWithoutKey), @('Keys lost', $st.KeysLost), @('Keys escrowed', $st.KeysEscrowed), @('Keys rotated', $st.KeysRotated), @('Encryption off', $st.EncryptionOff), @('Stopped syncing', $st.BecameStale)) foreach ($s in $stItems) { [void]$sb.Append("
$($s[1])$($s[0])
") } [void]$sb.Append("
") if ($st.Total -gt 0) { [void]$sb.Append("
") foreach ($ch in @($Diff.Changes)) { [void]$sb.Append("") } [void]$sb.Append("
SeverityChangeDeviceSerialUserDetail
$(Get-Badge $ch.Severity $ch.Severity)$(HE $ch.Category)$(HE $ch.DeviceName)$(HE $ch.SerialNumber)$(HE $ch.PrimaryUser)$(HE $ch.Detail)
") } else { [void]$sb.Append("

No change detected.

") } [void]$sb.Append("
") } # Action required $atRisk = @($Records | Where-Object { $_.Risk -ne 'OK' } | Sort-Object -Property @{ Expression = { $script:RiskOrder[$_.Risk] } }, DeviceName) [void]$sb.Append("

🔧 Devices requiring action

$($atRisk.Count) device(s) - click a column to sort
") if ($atRisk.Count -gt 0) { [void]$sb.Append("
") foreach ($d in $atRisk) { $sync = HE $d.LastSync if ($d.IsStale -eq $true) { $sync = "$sync" } $encTxt = 'No'; if ($d.IsEncrypted -eq $true) { $encTxt = 'Yes' } [void]$sb.Append("") } [void]$sb.Append("
RiskDeviceSerialUserStatusRecommended actionEncryptedLast sync
$(Get-Badge $d.Risk $d.Risk)$(HE $d.DeviceName)$(HE $d.SerialNumber)$(HE $d.PrimaryUser)$(HE $d.Status)$(HE $d.Recommendation)$encTxt$sync
") } else { [void]$sb.Append("

✅ Nothing to do: every device is protected.

") } [void]$sb.Append("
") # Breakdowns [void]$sb.Append("
") [void]$sb.Append((Get-BreakdownCardHtml 'By manufacturer' 'Top 10' (Get-Breakdown -Records $Records -Property 'Manufacturer' -Top 10) 'Manufacturer')) [void]$sb.Append((Get-BreakdownCardHtml 'By model' 'Top 12' (Get-Breakdown -Records $Records -Property { "$($_.Manufacturer) $($_.Model)" } -Top 12) 'Model')) [void]$sb.Append((Get-BreakdownCardHtml 'By OS build' 'Top 10' (Get-Breakdown -Records $Records -Property 'OSVersion' -Top 10) 'OS version')) [void]$sb.Append((Get-BreakdownCardHtml 'By join type' 'Entra joined / Hybrid / Registered' (Get-Breakdown -Records $Records -Property 'JoinType' -Top 10) 'Join type')) [void]$sb.Append((Get-BreakdownCardHtml 'By compliance state' 'Intune compliance' (Get-Breakdown -Records $Records -Property 'ComplianceState' -Top 10) 'Compliance')) [void]$sb.Append((Get-BreakdownCardHtml 'By sync freshness' "Stale = no sync for more than $($Ctx.StaleDays) days" (Get-Breakdown -Records $Records -Property { if ($_.IsStale -eq $true) { 'Stale' } else { 'Active' } } -Top 2) 'Sync')) [void]$sb.Append("
") # Orphans if (@($Orphans).Count -gt 0) { [void]$sb.Append("

🔑 Recovery keys of devices not managed by Intune

$(@($Orphans).Count) Entra device(s) still hold BitLocker keys but have no Intune record (retired, wiped, out of production). Review before deleting these Entra objects - deleting the device object deletes its keys.
") foreach ($o in @($Orphans | Sort-Object -Property LastKeyBackup -Descending)) { [void]$sb.Append("") } [void]$sb.Append("
Entra device nameEntra stateEntra device IDKeysLast key backup
$(HE $o.EntraName)$(HE $o.EntraState)$(HE $o.EntraDeviceId)$($o.KeyCount)$(HE $o.LastKeyBackup)
") } # Inventory [void]$sb.Append("

📋 Full inventory

$(@($Records).Count) device(s) shown - search on any column, filter by risk, click a header to sort
") [void]$sb.Append("
") [void]$sb.Append("
") foreach ($d in @($Records | Sort-Object -Property @{ Expression = { $script:RiskOrder[$_.Risk] } }, DeviceName)) { $stale = '0'; if ($d.IsStale -eq $true) { $stale = '1' } $sync = HE $d.LastSync if ($stale -eq '1') { $sync = "$sync" } $encTxt = 'No'; if ($d.IsEncrypted -eq $true) { $encTxt = 'Yes' } $lbl = $d.Risk; if ($lbl -eq 'OK') { $lbl = 'Protected' } [void]$sb.Append("") } [void]$sb.Append("
RiskDeviceSerialUserManufacturer / modelOSJoinComplianceEncryptedKeys (OS)Last key backupLast syncStatus
$(Get-Badge $lbl $d.Risk)$(HE $d.DeviceName)$(HE $d.SerialNumber)$(HE $d.PrimaryUser)$(HE $d.Manufacturer)
$(HE $d.Model)
$(HE $d.OSVersion)$(HE $d.JoinType)$(HE $d.ComplianceState)$encTxt$($d.KeyCount) ($($d.OsVolumeKeyCount))$(HE $d.LastKeyBackup)$sync$(HE $d.Status)
") # Legend [void]$sb.Append("

Legend & method

How each device is classified
") [void]$sb.Append("") [void]$sb.Append("") [void]$sb.Append("") [void]$sb.Append("") [void]$sb.Append("") [void]$sb.Append("") [void]$sb.Append("
$(Get-Badge 'Critical' 'Critical')Encrypted - NO key in Entra ID: the disk is encrypted but no recovery key is escrowed. A recovery prompt (BIOS/TPM update, hardware change) would mean data loss.
$(Get-Badge 'High' 'High')Not encrypted - no key (encryption policy not applied) or No Entra device ID (the device cannot escrow a key).
$(Get-Badge 'Medium' 'Medium')Key for data volume only (OS volume key missing) or key escrowed but Intune reports not encrypted (suspended BitLocker or outdated report).
$(Get-Badge 'Protected' 'OK')Encrypted and at least one OS volume recovery key escrowed in Entra ID.
StaleNo Intune sync for more than $($Ctx.StaleDays) days: candidate for retirement or out of production.
SourceIntune managedDevices (Windows) + Entra ID BitLocker recovery key metadata (ID, date, volume type). Recovery key values are never read nor exported.
") [void]$sb.Append("
BitLocker Key Escrow Monitor v$($Ctx.Version) · $(HE $Ctx.RunEnv) · generated $(HE $Ctx.GeneratedLocal)
") return $sb.ToString() } # ============================================================================ # 9. MAIL # ============================================================================ function New-MailAttachment { param([string]$Name, [byte[]]$Bytes, [string]$ContentType) return @{ '@odata.type' = '#microsoft.graph.fileAttachment' name = $Name contentType = $ContentType contentBytes = [Convert]::ToBase64String($Bytes) } } function Send-ReportMail { param([string]$Subject, [string]$HtmlBody, $Attachments, [string]$Importance = 'normal') $to = New-Object System.Collections.Generic.List[object] foreach ($r in ($Recipients -split '[,;]')) { $a = $r.Trim() if ($a) { $to.Add(@{ emailAddress = @{ address = $a } }) } } if ($to.Count -eq 0) { throw 'No valid recipient in -Recipients.' } $msg = @{ subject = $Subject importance = $Importance body = @{ contentType = 'HTML'; content = $HtmlBody } toRecipients = $to.ToArray() } if ($Attachments -and @($Attachments).Count -gt 0) { $msg['attachments'] = @($Attachments) } $payload = @{ message = $msg; saveToSentItems = $true } | ConvertTo-Json -Depth 10 -Compress $null = Invoke-Graph -Uri "https://graph.microsoft.com/v1.0/users/$SenderUPN/sendMail" -Method 'POST' -Body $payload } # ============================================================================ # 10. MAIN # ============================================================================ $runError = $null try { Write-Log "BitLocker Key Escrow Monitor v$ScriptVersion - start" 'STEP' $envLabel = 'Local' if ($script:IsAzureAutomation) { $envLabel = 'Azure Automation' } if ($DemoMode) { $envLabel = "$envLabel (DEMO)" } Write-Log "Environment: $envLabel - PowerShell $($PSVersionTable.PSVersion) - time zone $($script:TZ.Id)" if ([string]::IsNullOrWhiteSpace($OutputPath)) { if ($script:IsAzureAutomation) { $OutputPath = Join-Path $env:TEMP 'BitLockerReports' } else { $OutputPath = Join-Path (Get-Location).Path 'BitLockerReports' } } if (-not (Test-Path $OutputPath)) { New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null } $script:LocalStoreDir = $OutputPath $script:UseBlob = (-not [string]::IsNullOrWhiteSpace($StorageAccountName)) -and (-not $DemoMode) # --- Connections --------------------------------------------------------- if (-not $DemoMode) { Connect-GraphSession Write-Log 'Connected to Microsoft Graph' 'OK' if ($script:UseBlob) { if ($script:IsAzureAutomation) { $script:StorageToken = Get-MsiToken -Resource 'https://storage.azure.com/' } else { $script:StorageToken = Get-AzLocalToken -Resource 'https://storage.azure.com/' } try { $st = Initialize-StorageContainer -Container $ContainerName Write-Log "Snapshot storage: $StorageAccountName / $ContainerName ($st)" 'OK' if ($BackupRecoveryKeys) { try { $st2 = Initialize-StorageContainer -Container $KeyBackupContainer Write-Log "Key backup storage: $StorageAccountName / $KeyBackupContainer ($st2)" 'OK' } catch { Write-Log "Key backup container not usable: $($_.Exception.Message)" 'ERROR' } } } catch { $script:StorageError = $_.Exception.Message $script:UseBlob = $false Write-Log "AZURE STORAGE NOT USABLE - reports and snapshot will NOT be archived: $($script:StorageError)" 'ERROR' } } else { Write-Log "No StorageAccountName: snapshots are kept locally in $OutputPath only (lost after an Azure Automation job)." 'WARN' } } # --- Previous snapshot --------------------------------------------------- $previous = $null if (-not $DemoMode -and -not $ForceBaseline) { $prevText = Read-PreviousSnapshotText if ($prevText) { $previous = ConvertFrom-SnapshotJson -Text $prevText Write-Log ("Previous snapshot: {0} devices, generated {1} UTC" -f @($previous.Devices).Count, $previous.GeneratedUtc) 'OK' } else { Write-Log 'No previous snapshot: this run creates the BASELINE.' } } elseif ($ForceBaseline) { Write-Log 'ForceBaseline = true: previous snapshot ignored, a new baseline is created.' 'WARN' } # --- Data collection ----------------------------------------------------- $entraLoaded = $false $entraDevices = @() if ($DemoMode) { $demo = New-DemoData $intuneDevices = $demo.Devices $recoveryKeys = $demo.Keys $entraDevices = $demo.Entra $entraLoaded = $true Write-Log ("Demo data: {0} devices, {1} keys" -f @($intuneDevices).Count, @($recoveryKeys).Count) 'OK' } else { Write-Log 'Retrieving Windows devices from Intune...' 'STEP' $sel = 'id,deviceName,serialNumber,model,manufacturer,osVersion,azureADDeviceId,complianceState,isEncrypted,lastSyncDateTime,enrolledDateTime,userPrincipalName,managementAgent,joinType,managedDeviceOwnerType' $baseUri = "https://graph.microsoft.com/beta/deviceManagement/managedDevices?`$filter=operatingSystem%20eq%20'Windows'" try { $intuneDevices = Get-GraphAll -Uri ($baseUri + "&`$select=" + $sel) } catch { Write-Log "Query with select failed, retrying without select: $($_.Exception.Message)" 'WARN' $intuneDevices = Get-GraphAll -Uri $baseUri } Write-Log ("{0} Windows devices found in Intune" -f @($intuneDevices).Count) 'OK' Write-Log 'Retrieving BitLocker recovery key metadata (bulk, no key value)...' 'STEP' $recoveryKeys = Get-GraphAll -Uri 'https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys' Write-Log ("{0} recovery keys found in Entra ID" -f @($recoveryKeys).Count) 'OK' if ($IncludeEntraDevices) { Write-Log 'Retrieving Entra ID devices (enrichment / orphan keys)...' 'STEP' try { $entraDevices = Get-GraphAll -Uri "https://graph.microsoft.com/v1.0/devices?`$select=id,deviceId,displayName,accountEnabled,trustType,operatingSystem&`$top=999" $entraLoaded = $true Write-Log ("{0} Entra devices loaded" -f @($entraDevices).Count) 'OK' } catch { Write-Log "Entra devices not loaded (Device.Read.All missing?): $($_.Exception.Message)" 'WARN' } } } if (@($intuneDevices).Count -eq 0) { throw 'No Windows device returned by Intune - aborting to protect the reference snapshot (check DeviceManagementManagedDevices.Read.All).' } # --- Index keys and Entra devices ------------------------------------------ $keyMap = @{} foreach ($k in @($recoveryKeys)) { $kid = [string]$k.deviceId if ([string]::IsNullOrWhiteSpace($kid)) { continue } if (-not $keyMap.ContainsKey($kid)) { $keyMap[$kid] = [pscustomobject]@{ KeyCount = 0; OsKeyCount = 0; Latest = $null } } $e = $keyMap[$kid] $e.KeyCount = $e.KeyCount + 1 $vt = [string]$k.volumeType if ($vt -eq 'operatingSystemVolume' -or $vt -eq '1') { $e.OsKeyCount = $e.OsKeyCount + 1 } $dt = ConvertTo-UtcDate $k.createdDateTime if ($null -ne $dt) { if ($null -eq $e.Latest) { $e.Latest = $dt } elseif ($dt.Ticks -gt $e.Latest.Ticks) { $e.Latest = $dt } } } $entraMap = @{} foreach ($ed in @($entraDevices)) { if ($ed.deviceId) { $entraMap[[string]$ed.deviceId] = $ed } } $joinMap = @{ 'azureADJoined' = 'Entra joined'; 'hybridAzureADJoined' = 'Hybrid joined'; 'azureADRegistered' = 'Entra registered'; 'unknown' = 'Unknown' } # --- Build device records -------------------------------------------------- $nowUtc = (Get-Date).ToUniversalTime() $recordList = New-Object System.Collections.Generic.List[object] $aadInIntune = @{} foreach ($d in @($intuneDevices)) { $aad = [string]$d.azureADDeviceId $hasAad = -not ([string]::IsNullOrWhiteSpace($aad) -or $aad -eq '00000000-0000-0000-0000-000000000000') $kc = 0; $okc = 0; $latest = $null if ($hasAad) { $aadInIntune[$aad] = $true if ($keyMap.ContainsKey($aad)) { $kc = $keyMap[$aad].KeyCount; $okc = $keyMap[$aad].OsKeyCount; $latest = $keyMap[$aad].Latest } } $entraState = 'Not checked' if ($entraLoaded) { $entraState = 'Not found' if ($hasAad -and $entraMap.ContainsKey($aad)) { if ($entraMap[$aad].accountEnabled -eq $true) { $entraState = 'Enabled' } else { $entraState = 'Disabled' } } } $lastSync = ConvertTo-UtcDate $d.lastSyncDateTime $days = $null if ($lastSync) { $days = [int][math]::Floor(($nowUtc - $lastSync).TotalDays) } $isStale = ($null -ne $days -and $days -gt $StaleDays) $isEnc = ($d.isEncrypted -eq $true) $assess = Get-DeviceAssessment -HasAadId $hasAad -IsEncrypted $isEnc -KeyCount $kc -OsKeyCount $okc $join = [string]$d.joinType if ($joinMap.ContainsKey($join)) { $join = $joinMap[$join] } $hasKeyTxt = 'No'; if ($kc -gt 0) { $hasKeyTxt = 'Yes' } $recordList.Add([pscustomobject]@{ IntuneDeviceId = [string]$d.id DeviceName = [string]$d.deviceName SerialNumber = [string]$d.serialNumber PrimaryUser = [string]$d.userPrincipalName Manufacturer = [string]$d.manufacturer Model = [string]$d.model OSVersion = [string]$d.osVersion JoinType = $join Ownership = [string]$d.managedDeviceOwnerType ComplianceState = [string]$d.complianceState IsEncrypted = $isEnc AzureADDeviceId = $aad EntraState = $entraState HasRecoveryKey = $hasKeyTxt KeyCount = [int]$kc OsVolumeKeyCount = [int]$okc LastKeyBackup = (Format-Local $latest) LastKeyBackupUtc = (Format-Iso $latest) LastSync = (Format-Local $lastSync) LastSyncUtc = (Format-Iso $lastSync) DaysSinceSync = $days IsStale = $isStale Enrolled = (Format-Local (ConvertTo-UtcDate $d.enrolledDateTime) 'yyyy-MM-dd') Status = $assess.Status Risk = $assess.Risk Recommendation = $assess.Recommendation }) } # --- Orphan keys (keys whose device is not in Intune anymore) ------------ # PS 5.1: @() on a generic List throws "Argument types do not match" -> work on plain arrays $records = $recordList.ToArray() $orphanList = New-Object System.Collections.Generic.List[object] foreach ($kid in @($keyMap.Keys)) { if ($aadInIntune.ContainsKey($kid)) { continue } $e = $keyMap[$kid] $name = '(Entra lookup disabled)'; $state = 'Unknown' if ($entraLoaded) { $name = '(not found in Entra ID)'; $state = 'Deleted / unknown' if ($entraMap.ContainsKey($kid)) { $name = [string]$entraMap[$kid].displayName if ($entraMap[$kid].accountEnabled -eq $true) { $state = 'Enabled' } else { $state = 'Disabled' } } } $orphanList.Add([pscustomobject]@{ EntraDeviceId = $kid; EntraName = $name; EntraState = $state; KeyCount = $e.KeyCount; LastKeyBackup = (Format-Local $e.Latest 'yyyy-MM-dd') }) } $orphans = $orphanList.ToArray() $summary = Get-Summary -Records $records -GeneratedUtc (Format-Iso $nowUtc) -OrphanCount $orphans.Count -TotalKeys @($recoveryKeys).Count Write-Log ("Assessment done: {0} devices, coverage {1}%, critical {2}" -f $summary.TotalDevices, $summary.CoveragePct, $summary.Critical) 'OK' if ($DemoMode -and -not $ForceBaseline) { $previous = New-DemoPrevious -Records $records } # --- Delta ----------------------------------------------------------------- $diff = $null if ($previous) { $diff = Compare-BitLockerSnapshot -Previous @($previous.Devices) -Current $records -StaleThreshold $StaleDays Write-Log ("Delta: {0} change(s) - new {1}, removed {2}, re-enrolled {3}, keys lost {4}, keys escrowed {5}" -f $diff.Stats.Total, $diff.Stats.NewDevices, $diff.Stats.Removed, $diff.Stats.ReEnrolled, $diff.Stats.KeysLost, $diff.Stats.KeysEscrowed) 'OK' } $suspicious = $false if ($previous) { $pc = @($previous.Devices).Count if ($pc -ge 20 -and $records.Count -lt [math]::Floor($pc * 0.5)) { $suspicious = $true Write-Log "Device count dropped from $pc to $($records.Count): latest.json will NOT be updated." 'WARN' } } # --- Build files ------------------------------------------------------------- $localNow = [System.TimeZoneInfo]::ConvertTimeFromUtc($nowUtc, $script:TZ) $stamp = $localNow.ToString('yyyyMMdd-HHmm', $script:Invariant) $ym = $nowUtc.ToString('yyyy/MM', $script:Invariant) $htmlName = "BitLocker-Report-$stamp.html" $invName = "BitLocker-Inventory-$stamp.csv" $chgName = "BitLocker-Changes-$stamp.csv" $storageLabel = "local folder $OutputPath" if ($script:UseBlob) { $storageLabel = "$StorageAccountName / $ContainerName / reports/$ym" } elseif ($script:StorageError) { $storageLabel = "NOT SAVED to Azure Storage - $($script:StorageError)" } $prevLocal = '' if ($previous) { $prevLocal = Format-Local (ConvertTo-UtcDate $previous.GeneratedUtc) } $ctx = @{ Tenant = $TenantLabel GeneratedLocal = $localNow.ToString('yyyy-MM-dd HH:mm', $script:Invariant) Period = $localNow.ToString('MMMM yyyy', $script:Invariant) IsBaseline = ($null -eq $previous) PrevLocal = $prevLocal StaleDays = $StaleDays Storage = $storageLabel Suspicious = $suspicious Demo = [bool]$DemoMode Version = $ScriptVersion Backup = $null RunEnv = $envLabel MaxRows = $MaxEmailRows AttachmentList = '' AttachmentNote = '' } $utf8 = New-Object System.Text.UTF8Encoding($false) $fullHtml = New-FullHtmlReport -Summary $summary -Previous $previous -Diff $diff -Records $records -Orphans $orphans -Ctx $ctx $fullHtmlBytes = $utf8.GetBytes($fullHtml) $invBytes = ConvertTo-CsvBytes -Objects ($records | Select-Object -Property * -ExcludeProperty LastSyncUtc, LastKeyBackupUtc) -Delimiter $CsvDelimiter $chgBytes = $null if ($diff -and $diff.Stats.Total -gt 0) { $chgBytes = ConvertTo-CsvBytes -Objects $diff.Changes -Delimiter $CsvDelimiter } $snapshot = [pscustomobject]@{ SchemaVersion = 2 Tool = 'BitLockerKeyEscrowMonitor' ScriptVersion = $ScriptVersion Tenant = $TenantLabel GeneratedUtc = (Format-Iso $nowUtc) Summary = $summary Devices = $records } $snapshotBytes = $utf8.GetBytes(($snapshot | ConvertTo-Json -Depth 5 -Compress)) # --- Save reports + snapshot history ---------------------------------------- Write-Log 'Saving reports and snapshot...' 'STEP' Save-Artifact -RelativePath "reports/$ym/$htmlName" -Bytes $fullHtmlBytes -ContentType 'text/html; charset=utf-8' Save-Artifact -RelativePath "reports/$ym/$invName" -Bytes $invBytes -ContentType 'text/csv; charset=utf-8' if ($chgBytes) { Save-Artifact -RelativePath "reports/$ym/$chgName" -Bytes $chgBytes -ContentType 'text/csv; charset=utf-8' } if (-not $DemoMode) { Save-Artifact -RelativePath "snapshots/$ym/bitlocker-snapshot-$stamp.json" -Bytes $snapshotBytes -ContentType 'application/json; charset=utf-8' } Write-Log "Reports saved ($storageLabel)" 'OK' # --- Encrypted backup of the recovery key VALUES --------------------------------- $backup = [pscustomobject]@{ Enabled = [bool]$BackupRecoveryKeys; Status = 'Disabled'; Exported = 0; Failed = 0; Thumbprint = ''; Location = ''; Error = ''; CertWarning = ''; FileName = ''; Bytes = $null } if ($BackupRecoveryKeys) { try { $bCert = Get-BackupCertificate if (-not $bCert) { $backup.Status = 'Not configured' $backup.Error = "No backup certificate: create the Automation variable 'BitLockerBackupCert' with the base64 .cer (New-BitLockerBackupCertificate.ps1) or pass -KeyBackupCertificate." Write-Log $backup.Error 'WARN' } else { $backup.Thumbprint = $bCert.Thumbprint $daysLeft = [int]($bCert.NotAfter - (Get-Date)).TotalDays if ($daysLeft -lt 60) { $backup.CertWarning = "Backup certificate expires in $daysLeft day(s) ($($bCert.NotAfter.ToString('yyyy-MM-dd')))." } Write-Log ("Exporting {0} recovery key value(s) for the encrypted backup..." -f @($recoveryKeys).Count) 'STEP' $byAad = @{} foreach ($r in $records) { if ($r.AzureADDeviceId) { $byAad[$r.AzureADDeviceId] = $r } } $demoRnd = New-Object System.Random 7 $rows = New-Object System.Collections.Generic.List[object] $denied = 0 foreach ($k in @($recoveryKeys)) { try { if ($DemoMode) { $val = New-DemoRecoveryKey -Rnd $demoRnd } else { $kr = Invoke-Graph -Uri ("https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys/{0}?`$select=key" -f $k.id) $val = [string]$kr.key } if ([string]::IsNullOrWhiteSpace($val)) { throw 'Empty key value returned' } $did = [string]$k.deviceId $dev = $null; if ($byAad.ContainsKey($did)) { $dev = $byAad[$did] } $dName = ''; $serial = ''; $user = ''; $intuneId = ''; $inIntune = 'No' if ($dev) { $dName = $dev.DeviceName; $serial = $dev.SerialNumber; $user = $dev.PrimaryUser; $intuneId = $dev.IntuneDeviceId; $inIntune = 'Yes' } elseif ($entraMap.ContainsKey($did)) { $dName = [string]$entraMap[$did].displayName } $kid = [string]$k.id $short = $kid; if ($kid.Length -ge 8) { $short = $kid.Substring(0, 8).ToUpperInvariant() } $rows.Add([pscustomobject]@{ DeviceName = $dName SerialNumber = $serial PrimaryUser = $user InIntune = $inIntune EntraDeviceId = $did IntuneDeviceId = $intuneId RecoveryKeyId = $kid KeyIdShort = $short VolumeType = [string]$k.volumeType BackupDate = (Format-Local (ConvertTo-UtcDate $k.createdDateTime)) RecoveryKey = $val }) $backup.Exported++ $denied = 0 } catch { $backup.Failed++ Write-Warning ("Key {0} (device {1}) not exported: {2}" -f $k.id, $k.deviceId, $_.Exception.Message) if ($_.Exception.Message -match 'HTTP 403') { $denied++ } if ($denied -ge 3 -and $backup.Exported -eq 0) { throw 'Access denied reading key values: grant BitlockerKey.Read.All to the managed identity.' } } } if ($backup.Exported -eq 0) { throw 'No recovery key could be exported.' } $plain = ConvertTo-CsvBytes -Objects ($rows | Sort-Object DeviceName, BackupDate) -Delimiter $CsvDelimiter $rows.Clear(); $rows = $null $meta = @{ Tenant = $TenantLabel; CreatedUtc = (Format-Iso $nowUtc); KeyCount = $backup.Exported; FailedCount = $backup.Failed; CsvDelimiter = $CsvDelimiter; Demo = [bool]$DemoMode; ScriptVersion = $ScriptVersion } $envJson = Protect-BackupPayload -Data $plain -Cert $bCert -Meta $meta [Array]::Clear($plain, 0, $plain.Length); $plain = $null [System.GC]::Collect() $backup.FileName = "BitLocker-Keys-Backup-$stamp.bitlockerbackup.json" $backup.Bytes = $utf8.GetBytes($envJson) Save-Artifact -RelativePath "escrow/$ym/$($backup.FileName)" -Bytes $backup.Bytes -ContentType 'application/json' -Container $KeyBackupContainer Save-Artifact -RelativePath 'escrow/latest.bitlockerbackup.json' -Bytes $backup.Bytes -ContentType 'application/json' -Container $KeyBackupContainer if ($script:UseBlob) { $backup.Location = "$StorageAccountName / $KeyBackupContainer / escrow/$ym/$($backup.FileName)" } else { $backup.Location = "local folder $(Join-Path $OutputPath $KeyBackupContainer)" } $backup.Status = 'OK' if ($backup.Failed -gt 0) { $backup.Status = 'Partial' } if ($script:IsAzureAutomation -and -not $script:UseBlob -and -not $AttachKeyBackupToMail) { $backup.Status = 'Not stored' } Write-Log ("Encrypted key backup: {0} exported, {1} failed - {2}" -f $backup.Exported, $backup.Failed, $backup.Location) 'OK' } } catch { $backup.Status = 'FAILED' $backup.Error = $_.Exception.Message Write-Log "Encrypted key backup FAILED: $($backup.Error)" 'ERROR' } } $ctx.Backup = $backup # --- Mail ---------------------------------------------------------------------- $skipReason = '' if ($DemoMode) { $skipReason = 'demo mode' } elseif (-not $SendMail) { $skipReason = 'SendMail = false' } elseif ([string]::IsNullOrWhiteSpace($SenderUPN)) { $skipReason = 'SenderUPN is empty' } elseif ($MailOnlyWhenChanges -and $diff -and $diff.Stats.Total -eq 0 -and $summary.Critical -eq 0) { $skipReason = 'no change and no critical device' } $attachments = New-Object System.Collections.Generic.List[object] $attNames = New-Object System.Collections.Generic.List[string] $attachments.Add((New-MailAttachment -Name $invName -Bytes $invBytes -ContentType 'text/csv')) $attNames.Add($invName) if ($chgBytes) { $attachments.Add((New-MailAttachment -Name $chgName -Bytes $chgBytes -ContentType 'text/csv')); $attNames.Add($chgName) } if ($AttachKeyBackupToMail -and $backup.Bytes) { $attachments.Add((New-MailAttachment -Name $backup.FileName -Bytes $backup.Bytes -ContentType 'application/json')) $attNames.Add("$($backup.FileName) (encrypted key backup)") } if ($AttachFullHtml) { $used = 0 foreach ($a in $attachments) { $used += $a.contentBytes.Length } $htmlB64 = [math]::Ceiling($fullHtmlBytes.Length / 3) * 4 if (($used + $htmlB64) -le 2900000) { $attachments.Add((New-MailAttachment -Name $htmlName -Bytes $fullHtmlBytes -ContentType 'text/html')) $attNames.Add("$htmlName (open in a browser: search, filters, sort)") } else { $ctx.AttachmentNote = "The full HTML report is too large for e-mail: download $htmlName from $storageLabel." } } $ctx.AttachmentList = ($attNames -join ', ') $emailHtml = New-EmailHtml -Summary $summary -Previous $previous -Diff $diff -Records $records -Orphans $orphans -Ctx $ctx Save-Artifact -RelativePath "reports/$ym/BitLocker-Email-$stamp.html" -Bytes ($utf8.GetBytes($emailHtml)) -ContentType 'text/html; charset=utf-8' $mailSent = $false if ($skipReason) { Write-Log "Mail not sent: $skipReason" 'WARN' } else { $prefix = '[BitLocker]' if ($ctx.IsBaseline) { $prefix = '[BitLocker] BASELINE -' } $subject = '{0} {1} - {2} - Coverage {3}% - {4} critical / {5} missing key' -f $prefix, $TenantLabel, $ctx.Period, (Num $summary.CoveragePct), $summary.Critical, $summary.WithoutKey if ($diff -and $diff.Stats.KeysLost -gt 0) { $subject += " - $($diff.Stats.KeysLost) KEY(S) LOST" } if ($diff -and $diff.Stats.Total -gt 0) { $subject += " - $($diff.Stats.Total) change(s)" } if ($backup.Enabled -and $backup.Status -ne 'OK') { $subject += " - KEY BACKUP $($backup.Status.ToUpperInvariant())" } if ($script:StorageError) { $subject += ' - STORAGE ERROR' } $importance = 'normal' if ($summary.Critical -gt 0 -or ($diff -and $diff.Stats.KeysLost -gt 0) -or $suspicious -or ($backup.Enabled -and $backup.Status -ne 'OK') -or $script:StorageError) { $importance = 'high' } Write-Log "Sending report to $Recipients (from $SenderUPN)..." 'STEP' Send-ReportMail -Subject $subject -HtmlBody $emailHtml -Attachments $attachments.ToArray() -Importance $importance $mailSent = $true Write-Log 'Mail sent' 'OK' } # --- Update the reference snapshot (only after a successful mail) ---------- if ($DemoMode) { Write-Log 'Demo mode: reference snapshot not touched.' } elseif ($suspicious) { Write-Log 'Reference snapshot NOT updated (suspicious device count drop).' 'WARN' } else { Save-Artifact -RelativePath 'snapshots/latest.json' -Bytes $snapshotBytes -ContentType 'application/json; charset=utf-8' Write-Log 'Reference snapshot updated (snapshots/latest.json)' 'OK' } # --- Job output (plain lines: never truncated in Azure Automation) --------- $sep = '=' * 78 Write-Output '' Write-Output $sep Write-Output (" BITLOCKER KEY ESCROW REPORT - {0} - {1}" -f $TenantLabel, $ctx.GeneratedLocal) Write-Output $sep Write-Output (" Mode : {0}" -f $(if ($ctx.IsBaseline) { 'BASELINE' } else { "DELTA since $prevLocal" })) Write-Output (" Windows devices (Intune) : {0}" -f $summary.TotalDevices) Write-Output (" With recovery key in Entra ID : {0} ({1}%)" -f $summary.WithKey, (Num $summary.CoveragePct)) Write-Output (" Without recovery key : {0}" -f $summary.WithoutKey) Write-Output (" Critical (encrypted, no key): {0}" -f $summary.Critical) Write-Output (" High : {0}" -f $summary.High) Write-Output (" Medium : {0}" -f $summary.Medium) Write-Output (" Stale (> {0} days) : {1}" -f $StaleDays, $summary.Stale) Write-Output (" Orphan key devices : {0}" -f $summary.OrphanKeyDevices) if ($diff) { Write-Output (" Changes : {0} (new {1}, removed {2}, re-enrolled {3}, keys lost {4}, escrowed {5}, new w/o key {6})" -f $diff.Stats.Total, $diff.Stats.NewDevices, $diff.Stats.Removed, $diff.Stats.ReEnrolled, $diff.Stats.KeysLost, $diff.Stats.KeysEscrowed, $diff.Stats.NewWithoutKey) } Write-Output (" Reports : {0}" -f $storageLabel) if ($backup.Enabled) { Write-Output (" Encrypted key backup : {0} - {1} exported, {2} failed - {3}" -f $backup.Status, $backup.Exported, $backup.Failed, $(if ($backup.Location) { $backup.Location } else { $backup.Error })) } Write-Output (" Mail : {0}" -f $(if ($mailSent) { "sent to $Recipients" } else { "not sent ($skipReason)" })) Write-Output (" Duration : {0}" -f $script:Stopwatch.Elapsed.ToString('mm:ss')) Write-Output $sep $atRiskList = @($records | Where-Object { $_.Risk -ne 'OK' } | Sort-Object -Property @{ Expression = { $script:RiskOrder[$_.Risk] } }, DeviceName) if ($atRiskList.Count -gt 0) { Write-Output (" DEVICES REQUIRING ACTION ({0}) - first 200" -f $atRiskList.Count) foreach ($d in @($atRiskList | Select-Object -First 200)) { Write-Output (" [{0}] {1} | {2} | {3} | {4} | last sync {5}" -f $d.Risk, $d.DeviceName, $d.SerialNumber, $d.PrimaryUser, $d.Status, $d.LastSync) } Write-Output $sep } if ($diff -and $diff.Stats.Total -gt 0) { Write-Output (" CHANGES SINCE LAST SNAPSHOT ({0}) - first 200" -f $diff.Stats.Total) foreach ($c in @($diff.Changes | Select-Object -First 200)) { Write-Output (" [{0}] {1} | {2} | {3}" -f $c.Severity, $c.Category, $c.DeviceName, $c.Detail) } Write-Output $sep } if (-not $script:UseBlob) { Write-Output " Local files: $OutputPath" } Write-Log 'Completed successfully' 'OK' } catch { $runError = $_ Write-Log ("FAILED: {0}" -f $_.Exception.Message) 'ERROR' Write-Log ("At line {0}: {1}" -f $_.InvocationInfo.ScriptLineNumber, ([string]$_.InvocationInfo.Line).Trim()) 'ERROR' if ($_.ScriptStackTrace) { Write-Output $_.ScriptStackTrace } if (-not $DemoMode -and $SendMail -and -not [string]::IsNullOrWhiteSpace($SenderUPN) -and ($script:GraphToken -or $script:UseMgGraph)) { try { Send-ReportMail -Subject ("[BitLocker] Runbook FAILED - {0} - {1}" -f $TenantLabel, (Get-Date -Format 'yyyy-MM-dd')) -HtmlBody (New-FailureHtml -Message ($runError.Exception.Message)) -Attachments @() -Importance 'high' Write-Log 'Failure notification sent' 'WARN' } catch { Write-Log "Failure notification could not be sent: $($_.Exception.Message)" 'WARN' } } } finally { if ($script:UseMgGraph) { try { Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null } catch { } } } if ($runError) { throw $runError }