← Back to articles Security

Reverse Engineering a BitLocker Key Escrow Monitor for Intune, Entra ID, Azure Automation, and Encrypted Recovery Key Backups

Reverse Engineering a BitLocker Key Escrow Monitor for Intune, Entra ID, Azure Automation, and Encrypted Recovery Key Backups
🎬

Video Brief & Interactive Architecture Deck

Watch the walkthrough, explore the 16:9 interactive slide deck, or download PDF notes

▶️ Fullscreen Video ▶️ Watch on YouTube 🔔 Subscribe to MSEndpoint TV

Intune's built-in BitLocker compliance blade answers a comfortable question: Does this device report encryption enabled? Unfortunately, the question that saves you during a midnight firmware prompt or TPM lockout is completely different: Is a usable OS-volume recovery key actually escrowed in Microsoft Entra ID right now—and would we notice the week a key disappears or a device re-enrolls without one?

Architectural Scope & Design Goals
  • Bulk Graph Metadata (1 Paged Call vs. 2N Calls): Enumerates all recovery key metadata across the tenant in seconds (compared to 15–20 minutes for per-device Graph loops).
  • Pure REST in Azure Automation: Runs natively on Managed Identity inside PowerShell 5.1 or 7.x sandboxes without heavy Microsoft.Graph modules, while seamlessly supporting interactive Connect-MgGraph + offline -DemoMode $true testing locally.
  • Safety-First Snapshots & Delta Tracking: Compares each run against snapshots/latest.json (and aborts snapshot overwrite if the device count drops by >50% or email delivery fails).
  • Zero-Decrypt Offline Escrow: Wraps actual key values with AES-256-CBC + HMAC-SHA256 under a public .cer RSA-OAEP certificate—the runbook can encrypt, never decrypt.
ARCHITECTURE PIPELINE: CONTOSO BITLOCKER KEY ESCROW MONITOR 1. Bulk Graph Inventory • Intune Windows Devices • Entra RecoveryKey Metadata • Entra Devices (Orphan Check) Throttling-Aware REST (429/5xx) 2. Azure Automation Engine aa-contoso-intune · PS 5.1 / 7.x • Managed Identity (Graph + Blob) • Risk Classifier (Critical → OK) • Delta + Re-Enrolment Detector Guard: Abort latest.json if drop > 50% 3. Azure Blob Reports & Snapshots stcontosointune / bitlocker-reports • snapshots/yyyy/MM/ + latest.json • Standalone HTML Dashboard + CSV 4. Zero-Decrypt Recovery Escrow stcontosointune / bitlocker-escrow • AES-256-CBC + HMAC-SHA256 CSV • Wrapped with Public .cer (RSA-OAEP) Only offline PFX can decrypt; never in mail 5. Graph Mail & Commit Barrier /users/{SenderUPN}/sendMail • Outlook-Safe Inline-CSS Summary • Inventory CSV, Delta CSV & Full HTML Updates latest.json ONLY after Mail OK
Figure 1 : End-to-end execution architecture uniting bulk Microsoft Graph enumeration, Azure Automation Managed Identity, defensive snapshot diffing, and asymmetric RSA-OAEP recovery key escrow.

Required Permissions & Azure Prerequisites

Because the runbook supports both routine audit telemetry and optional encrypted key-value escrow, scope the Automation Account's system-assigned Managed Identity precisely to the permissions you use:

Layer Permission / Role Scope & Requirement Purpose
Microsoft Graph DeviceManagementManagedDevices.Read.All ✓ Required Inventory managed Windows endpoints, sync age, serials, and Intune encryption flag.
Microsoft Graph BitlockerKey.Read.All or BitlockerKey.ReadBasic.All ✓ Required ReadBasic covers audit mode; upgrade to Read.All when -BackupRecoveryKeys $true exports values.
Microsoft Graph Device.Read.All Optional Enriches orphan recovery keys (keys in Entra ID belonging to wiped/retired Intune devices).
Microsoft Graph Mail.Send (scope with Exchange RBAC for Applications) ✓ Required for Mail Sends HTML summary + CSV/HTML attachments from $SenderUPN.
Azure RBAC Storage Blob Data Contributor Report & Escrow containers Reads/writes snapshots/, reports/, and escrow/ blobs on stcontosointune.
Automation Variable BitLockerBackupCert Public .cer base64 only Unencrypted variable holding the public RSA certificate; private .pfx stays strictly offline.

Core Architectural Deep Dive

Rather than dumping all 800+ lines inline before explaining how the pieces fit together, below are the six engineering patterns that make this monitor reliable at enterprise scale—followed by the complete, ready-to-deploy check-bitlocker-keys.ps1 runbook at the bottom of the guide.

1. Managed Identity REST Auth & Throttling-Aware Graph Paging

In Azure Automation sandboxes, loading the full Microsoft.Graph module suite inflates cold start time and risks assembly conflicts under PowerShell 5.1. Detecting $env:IDENTITY_ENDPOINT and requesting bearer tokens via REST eliminates module dependencies in the cloud while retaining interactive Connect-MgGraph locally, backed by automatic 429 Retry-After and 5xx exponential backoff in Invoke-Graph.

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
}

# Paging loop respects @odata.nextLink across arbitrary tenant sizes
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())
}

2. One Paged Metadata Call Instead of 2N Per-Device Lookups

Calling BitLocker recovery key endpoints per device creates an O(N) Graph bottleneck (often 15–20 minutes and frequent 429 throttling). Instead, the runbook pulls /v1.0/informationProtection/bitlocker/recoveryKeys once in bulk and indexes every key in memory by deviceId, tracking total key count, OS-volume keys (operatingSystemVolume), and most recent backup timestamp—never touching secret key values during compliance evaluation.

$recoveryKeys = Get-GraphAll -Uri 'https://graph.microsoft.com/v1.0/informationProtection/bitlocker/recoveryKeys'
$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 -and ($null -eq $e.Latest -or $dt.Ticks -gt $e.Latest.Ticks)) {
        $e.Latest = $dt
    }
}

3. Risk Classification & Serial-Matched Re-Enrolment Delta Engine

By indexing both IntuneDeviceId and hardware SerialNumber (excluding generic OEM placeholder strings like Default string or To be filled...), Compare-BitLockerSnapshot distinguishes a genuinely newly procured laptop from an Autopilot wipe/re-enrolment that spawned a brand-new Intune device GUID, while raising immediate Critical alerts whenever an encrypted machine loses all escrowed keys.

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 = 'Check 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 = 'Run BackupToAAD-BitLockerKeyProtector or rotate key via Intune.' }
    }
    if ($KeyCount -eq 0) {
        return [pscustomobject]@{ Status = 'Not encrypted - no key'; Risk = 'High'; Recommendation = 'Verify BitLocker policy assignment & TPM readiness.' }
    }
    if ($OsKeyCount -eq 0) {
        return [pscustomobject]@{ Status = 'Key for data volume only'; Risk = 'Medium'; Recommendation = 'Escrow C: OS volume key via BackupToAAD-BitLockerKeyProtector.' }
    }
    if (-not $IsEncrypted) {
        return [pscustomobject]@{ Status = 'Key escrowed - Intune reports not encrypted'; Risk = 'Medium'; Recommendation = 'Verify manage-bde -status for suspended BitLocker.' }
    }
    return [pscustomobject]@{ Status = 'Protected'; Risk = 'OK'; Recommendation = 'No action.' }
}

4. Zero-Decrypt Offline Key Escrow (AES-256-CBC + HMAC-SHA256 + RSA-OAEP)

When -BackupRecoveryKeys $true is enabled, the runbook encrypts exported CSV recovery keys inside memory using a fresh ephemeral 256-bit AES key plus a separate 256-bit HMAC key (encrypt-then-MAC), wraps the concatenated 64-byte secret using the public key only from BitLockerBackupCert (explicitly aborting if a certificate accidentally includes a private key), and clears all plaintext byte buffers immediately afterwards.

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)
    $tag = (New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList (, $macKey)).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)
    $wrapped = $rsa.Encrypt($secret, [System.Security.Cryptography.RSAEncryptionPadding]::OaepSHA256)
    [Array]::Clear($secret, 0, $secret.Length); [Array]::Clear($macKey, 0, $macKey.Length)
    ...
}

5. Outlook-Safe Mail vs. Interactive HTML Dashboard & Safe Commit Barrier

Email clients strip modern CSS and JavaScript, whereas browsers thrive on them. The runbook builds two distinct HTML artifacts: an inline-styled, table-based executive digest for Outlook, and a standalone interactive dashboard attachment (conic-gradient coverage gauge, instant search, risk filter pills, and sortable columns). Crucially, snapshots/latest.json is written only after Graph sendMail succeeds and only if the device count has not dropped by >50%.

# Guard against partial Graph responses wiping out the delta baseline
$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'
    }
}

# Update reference snapshot ONLY after email delivery succeeds
Send-ReportMail -Subject $subject -HtmlBody $emailHtml -Attachments $attachments.ToArray() -Importance $importance
if (-not $DemoMode -and -not $suspicious) {
    Save-Artifact -RelativePath 'snapshots/latest.json' -Bytes $snapshotBytes -ContentType 'application/json; charset=utf-8'
}

📊 Sample Output: Nexora Cloud Systems

Example run on a fictional company with 1,066 Windows devices: 97.9% coverage, 13 critical devices without a recovery key, and 245 orphan keys.

BitLocker monthly email report for Nexora Cloud Systems
Monthly email report sent by the runbook.
Interactive HTML BitLocker report dashboard
Attached HTML report: coverage, risk levels and devices to fix.
Open the interactive report ↗

6. Azure Automation Deployment & Scheduling

  1. Provision & Configure the Runbook: Create a PowerShell 5.1 runbook inside your Automation Account (e.g., aa-contoso-intune/check-bitlocker-keys), enable its system-assigned Managed Identity, grant the Graph application permissions listed above, and assign Storage Blob Data Contributor on your Azure Storage account (stcontosointune).
    Azure Portal Automation runbook overview for check-bitlocker-keys in aa-contoso-intune
    Figure 2 : Azure Portal path Home > aa-contoso-intune > Runbooks > check-bitlocker-keys Overview blade confirming PowerShell 5.1 runtime configuration and recent completed job telemetry.
  2. Validate Locally with Demo Mode Before First Cloud Run: Run .\check-bitlocker-keys.ps1 -DemoMode $true locally with zero permissions required to inspect the generated Baseline + Delta reports, CSVs, and Outlook HTML output under .\BitLockerReports.
  3. Schedule Monthly or Weekly Cadence in Azure Automation: Link a recurring schedule (e.g., Monthly / 1st of month) under Schedules with Recipients, SenderUPN, and StorageAccountName parameters populated, leaving BackupRecoveryKeys = $true if BitLockerBackupCert is configured.
    Azure Automation runbook schedule blade showing recurring Bitlocker Monthly Reports enabled
    Figure 3 : Azure Portal > aa-contoso-intune/check-bitlocker-keys > Schedules blade verifying the active recurring schedule bound to runbook parameters.
Security & Operations Caveat Never store your offline backup certificate's private key (.pfx) in Azure Automation Variables or Key Vault accessible to the same Managed Identity that reads recovery keys. Keeping only the public .cer in BitLockerBackupCert enforces strict write-only cryptographic escrow. Also double-check Recipients and Exchange Application RBAC before enabling automated delivery in production.

Complete Production Runbook (Ready to Deploy)

Below is the complete, tested, anonymized PowerShell 5.1 / 7.x runbook (check-bitlocker-keys.ps1) with every helper, delta comparator, REST paging handler, cryptographic escrow module, and HTML report generator intact. Use Copy Full Script or download check-bitlocker-keys.ps1 directly.

📜 Complete Ready-to-Deploy Script
BitLocker Key Escrow Monitor (Azure Automation Runbook) (check-bitlocker-keys.ps1 · 1678 lines · Anonymized)
📜 Complete PowerShell Runbook (1678 lines — click to collapse/expand)
<#
.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: <container>/snapshots/yyyy/MM/bitlocker-snapshot-<stamp>.json + snapshots/latest.json
Reports: <container>/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
(<KeyBackupContainer>/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 = <storage account>
.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 "<span style='display:inline-block;padding:2px 9px;border-radius:10px;font-size:11px;font-weight:700;white-space:nowrap;color:$($p.Fg);background-color:$($p.Bg);'>$(HE $Text)</span>"
}
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>([^<]+)</Code>') { $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 '&nbsp;' }
$d = [double]$Current - [double]$Previous
if ([math]::Abs($d) -lt 0.05) { return "<span style='color:#94a3b8;'>= vs last run</span>" }
$sign = ''
if ($d -gt 0) { $sign = '+' }
$col = '#64748b'
if (-not $Neutral) {
if (($d -gt 0) -eq $HigherIsBetter) { $col = '#16a34a' } else { $col = '#dc2626' }
}
return "<span style='color:$col;font-weight:600;'>$sign$(Num $d)$Suffix vs last run</span>"
}
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 "<td align='center' width='25%' style='padding:18px 6px;$border$($script:F)'><div style='font-size:28px;font-weight:700;color:$Color;'>$Value</div><div style='font-size:10px;letter-spacing:.6px;text-transform:uppercase;color:#64748b;font-weight:700;margin-top:4px;'>$Label</div><div style='font-size:11px;margin-top:4px;'>$Sub</div></td>"
}
function Get-EmailCard {
param([string]$Title, [string]$Subtitle, [string]$Inner)
$sub = ''
if ($Subtitle) { $sub = "<div style='font-size:12px;font-weight:400;color:#64748b;margin-top:3px;'>$Subtitle</div>" }
return "<tr><td style='padding-top:16px;'><table role='presentation' width='100%' cellpadding='0' cellspacing='0' border='0' style='background-color:#ffffff;border:1px solid #e2e8f0;border-radius:10px;'><tr><td style='padding:16px 20px 6px 20px;$($script:F)font-size:15px;font-weight:700;color:#0f172a;'>$Title$sub</td></tr><tr><td style='padding:8px 20px 18px 20px;$($script:F)'>$Inner</td></tr></table></td></tr>"
}
function Get-EmailTableHead {
param([string[]]$Headers)
$h = "<table role='presentation' width='100%' cellpadding='0' cellspacing='0' border='0' style='border-collapse:collapse;$($script:F)'><tr>"
foreach ($x in $Headers) {
$h += "<th align='left' style='background-color:#f8fafc;color:#475569;font-size:10px;text-transform:uppercase;letter-spacing:.5px;padding:8px;border-bottom:1px solid #e2e8f0;'>$x</th>"
}
return $h + '</tr>'
}
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 &middot; generated $(HE $Ctx.GeneratedLocal) (Paris time)"
if (-not $Ctx.IsBaseline) { $modeLine = "Report $(HE $Ctx.Period) &middot; changes since $(HE $Ctx.PrevLocal) &middot; generated $(HE $Ctx.GeneratedLocal)" }
if ($Ctx.Demo) { $modeLine = "DEMO DATA &middot; $modeLine" }
[void]$sb.Append("<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><meta name='viewport' content='width=device-width, initial-scale=1.0'></head>")
[void]$sb.Append("<body style='margin:0;padding:0;background-color:#f1f5f9;'><table role='presentation' width='100%' cellpadding='0' cellspacing='0' border='0' style='background-color:#f1f5f9;'><tr><td align='center' style='padding:24px 10px;'>")
[void]$sb.Append("<table role='presentation' width='720' cellpadding='0' cellspacing='0' border='0' style='width:720px;max-width:720px;'>")
# Header
[void]$sb.Append("<tr><td style='background-color:#1e3a8a;padding:28px 30px;border-radius:10px 10px 0 0;$F'>")
[void]$sb.Append("<div style='font-size:11px;color:#93c5fd;letter-spacing:1.2px;text-transform:uppercase;font-weight:700;'>$(HE $Ctx.Tenant) &middot; Intune &amp; Entra ID</div>")
[void]$sb.Append("<div style='font-size:24px;color:#ffffff;font-weight:700;margin-top:6px;'>&#128272; BitLocker Recovery Key Report</div>")
[void]$sb.Append("<div style='font-size:13px;color:#bfdbfe;margin-top:6px;'>$modeLine</div></td></tr>")
# KPIs
$pS = $null; if ($prevSum) { $pS = $prevSum }
$dTot = '&nbsp;'; $dWith = '&nbsp;'; $dMiss = '&nbsp;'; $dCov = '&nbsp;'
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("<tr><td style='background-color:#ffffff;border-bottom:1px solid #e2e8f0;'><table role='presentation' width='100%' cellpadding='0' cellspacing='0' border='0'><tr>")
[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("</tr></table></td></tr>")
# Banner
$bBg = '#dcfce7'; $bFg = '#166534'; $bBar = '#16a34a'
$bText = "&#9989; 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 = "&#9888;&#65039; $($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 = "&#128680; $($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 += "<br/>&#10060; $($Diff.Stats.KeysLost) device(s) LOST their escrowed key since the last run." }
if ($Ctx.Suspicious) {
$bBg = '#fee2e2'; $bFg = '#991b1b'; $bBar = '#dc2626'
$bText = "&#128680; 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("<tr><td style='background-color:$bBg;padding:14px 22px;color:$bFg;font-size:13px;font-weight:600;border-left:5px solid $bBar;$F'>$bText</td></tr>")
# 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 = "<td width='$w%' style='background-color:#16a34a;height:12px;font-size:0;line-height:0;'>&nbsp;</td>"
if ($w -lt 100) { $barCells += "<td width='$(100 - $w)%' style='background-color:#fecaca;height:12px;font-size:0;line-height:0;'>&nbsp;</td>" }
$riskLine = "$(Get-Badge "Critical $($Summary.Critical)" 'Critical') &nbsp; $(Get-Badge "High $($Summary.High)" 'High') &nbsp; $(Get-Badge "Medium $($Summary.Medium)" 'Medium') &nbsp; $(Get-Badge "Protected $($Summary.OK)" 'OK')"
$extra = "Encrypted (Intune): <b>$($Summary.Encrypted)</b> &middot; Not synced for &gt; $($Ctx.StaleDays) days: <b>$($Summary.Stale)</b> &middot; Recovery keys in tenant: <b>$($Summary.TotalKeys)</b>"
[void]$sb.Append("<tr><td style='background-color:#ffffff;padding:18px 22px;border-radius:0 0 10px 10px;$F'><div style='font-size:12px;color:#475569;font-weight:700;margin-bottom:8px;'>KEY ESCROW COVERAGE</div><table role='presentation' width='100%' cellpadding='0' cellspacing='0' border='0'><tr>$barCells</tr></table><div style='margin-top:12px;'>$riskLine</div><div style='font-size:12px;color:#64748b;margin-top:10px;'>$extra</div></td></tr>")
# Changes / baseline
if ($Ctx.IsBaseline) {
$inner = "<div style='font-size:13px;color:#334155;line-height:1.6;'>This is the <b>first snapshot</b>: 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.</div>"
[void]$sb.Append((Get-EmailCard '&#128204; 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 = "<table role='presentation' width='100%' cellpadding='0' cellspacing='4' border='0'><tr>"
foreach ($c in $chips) {
$col = '#94a3b8'; if ([int]$c[1] -gt 0) { $col = $c[2] }
$chipHtml += "<td align='center' style='background-color:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:8px 2px;$F'><div style='font-size:18px;font-weight:700;color:$col;'>$($c[1])</div><div style='font-size:9px;text-transform:uppercase;color:#64748b;font-weight:700;'>$($c[0])</div></td>"
}
$chipHtml += "</tr></table>"
$tbl = ''
if ($st.Total -gt 0) {
$tbl = "<div style='height:12px;line-height:12px;'>&nbsp;</div>" + (Get-EmailTableHead @('Severity', 'Change', 'Device', 'Detail'))
foreach ($ch in @($Diff.Changes | Select-Object -First $Ctx.MaxRows)) {
$tbl += "<tr><td style='$td'>$(Get-Badge $ch.Severity $ch.Severity)</td><td style='$td font-weight:600;'>$(HE $ch.Category)</td><td style='$td'><b>$(HE $ch.DeviceName)</b><br/><span style='color:#94a3b8;font-size:11px;'>$(HE $ch.PrimaryUser)</span></td><td style='$td'>$(HE $ch.Detail)</td></tr>"
}
$tbl += '</table>'
if ($st.Total -gt $Ctx.MaxRows) { $tbl += "<div style='font-size:12px;color:#64748b;margin-top:8px;'>+ $($st.Total - $Ctx.MaxRows) more change(s) in the attached report / CSV.</div>" }
}
else {
$tbl = "<div style='font-size:13px;color:#64748b;margin-top:12px;'>No change detected since the previous snapshot.</div>"
}
[void]$sb.Append((Get-EmailCard '&#128260; 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 = "<span style='color:#dc2626;font-weight:600;'>$sync</span>" }
$tbl += "<tr><td style='$td'>$(Get-Badge $d.Risk $d.Risk)</td><td style='$td'><b>$(HE $d.DeviceName)</b><br/><span style='color:#94a3b8;font-size:11px;'>$(HE $d.SerialNumber)</span></td><td style='$td'>$(HE $d.PrimaryUser)</td><td style='$td'><b>$(HE $d.Status)</b><br/><span style='color:#64748b;font-size:11px;'>$(HE $d.Recommendation)</span></td><td style='$td white-space:nowrap;'>$sync</td></tr>"
}
$tbl += '</table>'
if ($atRisk.Count -gt $Ctx.MaxRows) { $tbl += "<div style='font-size:12px;color:#64748b;margin-top:8px;'>+ $($atRisk.Count - $Ctx.MaxRows) more device(s) in the attached report / CSV.</div>" }
[void]$sb.Append((Get-EmailCard '&#128295; 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 = "<span style='color:#94a3b8;'>0</span>"; if ($r.Missing -gt 0) { $miss = "<b style='color:#dc2626;'>$($r.Missing)</b>" }
$tbl += "<tr><td style='$td'>$(HE $r.Name)</td><td style='$td'>$($r.Total)</td><td style='$td'>$miss</td><td style='$td color:$col;font-weight:700;'>$(Num $r.Coverage)%</td></tr>"
}
$tbl += '</table>'
[void]$sb.Append((Get-EmailCard '&#128187; Coverage by manufacturer' '' $tbl))
# Orphans + attachments
$foot = ''
if (@($Orphans).Count -gt 0) {
$foot += "<div style='font-size:12px;color:#334155;margin-bottom:8px;'>&#128273; <b>$(@($Orphans).Count)</b> 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.</div>"
}
$foot += "<div style='font-size:12px;color:#334155;'>&#128206; Attachments: $(HE $Ctx.AttachmentList)</div>"
if ($Ctx.AttachmentNote) { $foot += "<div style='font-size:12px;color:#9a3412;margin-top:6px;'>$(HE $Ctx.AttachmentNote)</div>" }
$foot += "<div style='font-size:12px;color:#334155;margin-top:6px;'>&#128190; Archive: $(HE $Ctx.Storage)</div>"
$bk = $Ctx.Backup
if ($bk -and $bk.Enabled) {
$kind = 'OK'; $title = '&#128274; Recovery key backup (encrypted)'
$txt = "<b>$($bk.Exported)</b> recovery key(s) exported and encrypted with the offline certificate (thumbprint <span style='font-family:Consolas,monospace;'>$(HE $bk.Thumbprint)</span>).<br/>Location: $(HE $bk.Location)"
if ($bk.Status -eq 'Partial') { $kind = 'High'; $txt += "<br/><b style='color:#9a3412;'>$($bk.Failed) key(s) could not be read</b> - check the job output." }
elseif ($bk.Status -eq 'Not stored') { $kind = 'High'; $txt += "<br/><b style='color:#9a3412;'>No StorageAccountName: the backup file was NOT kept.</b>" }
elseif ($bk.Status -ne 'OK') { $kind = 'Critical'; $txt = "<b style='color:#991b1b;'>Backup $(HE $bk.Status)</b>: $(HE $bk.Error)" }
if ($bk.CertWarning) { $txt += "<br/><b style='color:#9a3412;'>$(HE $bk.CertWarning)</b>" }
$txt += "<br/><span style='color:#64748b;font-size:11px;'>Key values never appear in this e-mail. Decrypt offline with Restore-BitLockerKeys.ps1 and the PFX.</span>"
[void]$sb.Append((Get-EmailCard $title '' ("$(Get-Badge $bk.Status $kind)<div style='font-size:12px;color:#334155;margin-top:8px;line-height:1.6;'>$txt</div>")))
}
[void]$sb.Append((Get-EmailCard '&#8505;&#65039; Details' '' $foot))
[void]$sb.Append("<tr><td align='center' style='padding:18px 0 0 0;color:#94a3b8;font-size:11px;$F'>BitLocker Key Escrow Monitor v$($Ctx.Version) &middot; $(HE $Ctx.RunEnv) &middot; recovery key values are never read nor exported</td></tr>")
[void]$sb.Append("</table></td></tr></table></body></html>")
return $sb.ToString()
}
function New-FailureHtml {
param([string]$Message)
return "<html><body style='margin:0;padding:20px;background-color:#f1f5f9;$($script:F)'><table width='640' cellpadding='0' cellspacing='0' border='0' style='background-color:#ffffff;border-top:5px solid #dc2626;border-radius:8px;'><tr><td style='padding:22px;'><div style='font-size:20px;font-weight:700;color:#991b1b;'>BitLocker Key Escrow Monitor - run FAILED</div><div style='font-size:13px;color:#334155;margin-top:12px;'>The reference snapshot was not updated. Error:</div><pre style='white-space:pre-wrap;background-color:#f8fafc;border:1px solid #e2e8f0;padding:12px;font-size:12px;color:#0f172a;'>$(HE $Message)</pre></td></tr></table></body></html>"
}
# ============================================================================
# 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("<div class='card'><h2>$(HE $Title)</h2><div class='sub'>$(HE $Subtitle)</div><table class='t'><thead><tr><th>$(HE $NameHeader)</th><th class='r'>Devices</th><th class='r'>Missing</th><th style='width:40%'>Coverage</th></tr></thead><tbody>")
foreach ($r in @($Rows)) {
$col = '#16a34a'; if ($r.Coverage -lt 98) { $col = '#ca8a04' }; if ($r.Coverage -lt 90) { $col = '#dc2626' }
$miss = "<span class='muted'>0</span>"; if ($r.Missing -gt 0) { $miss = "<b style='color:#dc2626'>$($r.Missing)</b>" }
[void]$sb.Append("<tr><td>$(HE $r.Name)</td><td class='r'>$($r.Total)</td><td class='r'>$miss</td><td><div class='cov'><div class='bar'><i style='width:$(Num $r.Coverage)%;background:$col'></i></div><span>$(Num $r.Coverage)%</span></div></td></tr>")
}
[void]$sb.Append('</tbody></table></div>')
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<rows.length;i++){
var r=rows[i];
var ok=(r.textContent.toLowerCase().indexOf(t)>-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;i<b.length;i++){
b[i].addEventListener('click',function(){
for(var j=0;j<b.length;j++){b[j].classList.remove('on');}
this.classList.add('on'); rf=this.getAttribute('data-r'); apply();
});
}
var tables=document.querySelectorAll('table.sortable');
for(var k=0;k<tables.length;k++){(function(tbl){
var ths=tbl.querySelectorAll('thead th');
for(var c=0;c<ths.length;c++){(function(idx,th){
th.addEventListener('click',function(){
var dir=th.getAttribute('data-dir')==='asc'?-1:1;
th.setAttribute('data-dir',dir===1?'asc':'desc');
var body=tbl.tBodies[0], rows=Array.prototype.slice.call(body.rows);
rows.sort(function(a,b){
var x=a.cells[idx].getAttribute('data-v')||a.cells[idx].textContent.trim();
var y=b.cells[idx].getAttribute('data-v')||b.cells[idx].textContent.trim();
var nx=Number(x), ny=Number(y);
if(x!==''&&y!==''&&!isNaN(nx)&&!isNaN(ny)){return (nx-ny)*dir;}
return x.localeCompare(y)*dir;
});
for(var r=0;r<rows.length;r++){body.appendChild(rows[r]);}
});
})(c,ths[c]);}
})(tables[k]);}
})();
'@
$prevSum = $null
if ($Previous) { $prevSum = $Previous.Summary }
$sb = New-Object System.Text.StringBuilder
[void]$sb.Append("<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>BitLocker Recovery Key Report - $(HE $Ctx.Tenant) - $(HE $Ctx.GeneratedLocal)</title><style>$css</style></head><body>")
# HERO
$mode = 'Initial baseline'
if (-not $Ctx.IsBaseline) { $mode = "Delta since $($Ctx.PrevLocal)" }
if ($Ctx.Demo) { $mode = "DEMO DATA - $mode" }
[void]$sb.Append("<div class='hero'><div class='eyebrow'>$(HE $Ctx.Tenant) &middot; Intune &amp; Entra ID</div><h1>&#128272; BitLocker Recovery Key Report</h1><p>Escrow status of BitLocker recovery keys for every Windows device managed by Intune - $(HE $Ctx.Period)</p><div class='chips'>")
[void]$sb.Append("<span class='chip'>Generated $(HE $Ctx.GeneratedLocal) (Paris)</span><span class='chip'>$(HE $mode)</span><span class='chip'>Stale threshold: $($Ctx.StaleDays) days</span><span class='chip'>Archive: $(HE $Ctx.Storage)</span><span class='chip'>v$($Ctx.Version)</span></div></div><div class='wrap'>")
# KPIs
$kp = @(
@("$($Summary.TotalDevices)", 'Windows devices', '#0f172a', $(if ($prevSum) { Get-DeltaHtml $Summary.TotalDevices $prevSum.TotalDevices '' $true $true } else { '&nbsp;' })),
@("$($Summary.WithKey)", 'Key escrowed', '#16a34a', $(if ($prevSum) { Get-DeltaHtml $Summary.WithKey $prevSum.WithKey '' $true } else { '&nbsp;' })),
@("$($Summary.WithoutKey)", 'Missing key', $(if ($Summary.WithoutKey -gt 0) { '#dc2626' } else { '#16a34a' }), $(if ($prevSum) { Get-DeltaHtml $Summary.WithoutKey $prevSum.WithoutKey '' $false } else { '&nbsp;' })),
@("$(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 { '&nbsp;' })),
@("$($Summary.Critical)", 'Critical', '#dc2626', 'Encrypted, no key'),
@("$($Summary.Stale)", 'Stale devices', '#ca8a04', "No sync &gt; $($Ctx.StaleDays) days"),
@("$($Summary.OrphanKeyDevices)", 'Orphan keys', '#7c3aed', 'Keys of unmanaged devices')
)
[void]$sb.Append("<div class='kpis'>")
foreach ($k in $kp) { [void]$sb.Append("<div class='kpi' style='--c:$($k[2])'><div class='v'>$($k[0])</div><div class='l'>$($k[1])</div><div class='s'>$($k[3])</div></div>") }
[void]$sb.Append("</div>")
# Banner
$bBg = '#dcfce7'; $bFg = '#166534'; $bBar = '#16a34a'
$bText = "&#9989; 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 = "&#9888;&#65039; $($Summary.WithoutKey) device(s) have no recovery key in Entra ID." }
if ($Summary.Critical -gt 0) { $bBg = '#fee2e2'; $bFg = '#991b1b'; $bBar = '#dc2626'; $bText = "&#128680; $($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 = "&#128680; Device count dropped by more than 50 % - possible partial data: the reference snapshot was NOT updated. " + $bText }
[void]$sb.Append("<div class='banner' style='background:$bBg;color:$bFg;border-color:$bBar'>$bText</div>")
# Gauge + risk distribution
$tot = [math]::Max(1, [int]$Summary.TotalDevices)
[void]$sb.Append("<div class='grid2'><div class='card'><h2>Key escrow coverage</h2><div class='sub'>Devices with at least one recovery key stored in Entra ID</div><div class='gaugebox'><div class='gauge' style='--p:$(Num $Summary.CoveragePct)'><div><b>$(Num $Summary.CoveragePct)%</b><span>covered</span></div></div><div class='facts' style='flex:1;min-width:220px'>")
[void]$sb.Append("<div><b>$($Summary.WithKey)</b> devices with a key</div><div><b>$($Summary.WithoutKey)</b> devices without key</div><div><b>$($Summary.Encrypted)</b> encrypted (Intune report)</div><div><b>$($Summary.NoEntraId)</b> without Entra device ID</div><div><b>$($Summary.TotalKeys)</b> recovery keys in the tenant</div></div></div></div>")
[void]$sb.Append("<div class='card'><h2>Risk distribution</h2><div class='sub'>Classification of each device (see legend at the bottom)</div>")
foreach ($rk in @('Critical', 'High', 'Medium', 'OK')) {
$n = [int]$Summary.$rk
$lbl = $rk; if ($rk -eq 'OK') { $lbl = 'Protected' }
[void]$sb.Append("<div class='riskrow'><span class='lbl'>$(Get-Badge $lbl $rk)</span><div class='bar'><i style='width:$(Num (100.0 * $n / $tot))%;background:$($script:Palette[$rk].Bar)'></i></div><span class='n'>$n</span></div>")
}
[void]$sb.Append("</div></div>")
# Changes
if ($Ctx.IsBaseline) {
[void]$sb.Append("<div class='card'><h2>&#128204; Baseline created</h2><div class='sub'>No previous snapshot</div><p>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.</p></div>")
}
else {
$st = $Diff.Stats
[void]$sb.Append("<div class='card'><h2>&#128260; Changes since the last snapshot</h2><div class='sub'>$($st.Total) change(s) between $(HE $Ctx.PrevLocal) and $(HE $Ctx.GeneratedLocal)</div><div class='stats'>")
$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("<div class='stat'><b>$($s[1])</b><span>$($s[0])</span></div>") }
[void]$sb.Append("</div>")
if ($st.Total -gt 0) {
[void]$sb.Append("<div class='scroll'><table class='t sortable'><thead><tr><th>Severity</th><th>Change</th><th>Device</th><th>Serial</th><th>User</th><th>Detail</th></tr></thead><tbody>")
foreach ($ch in @($Diff.Changes)) {
[void]$sb.Append("<tr><td data-v='$($script:SevOrder[$ch.Severity])'>$(Get-Badge $ch.Severity $ch.Severity)</td><td><b>$(HE $ch.Category)</b></td><td>$(HE $ch.DeviceName)</td><td class='mono'>$(HE $ch.SerialNumber)</td><td>$(HE $ch.PrimaryUser)</td><td>$(HE $ch.Detail)</td></tr>")
}
[void]$sb.Append("</tbody></table></div>")
}
else { [void]$sb.Append("<p class='muted'>No change detected.</p>") }
[void]$sb.Append("</div>")
}
# Action required
$atRisk = @($Records | Where-Object { $_.Risk -ne 'OK' } | Sort-Object -Property @{ Expression = { $script:RiskOrder[$_.Risk] } }, DeviceName)
[void]$sb.Append("<div class='card'><h2>&#128295; Devices requiring action</h2><div class='sub'>$($atRisk.Count) device(s) - click a column to sort</div>")
if ($atRisk.Count -gt 0) {
[void]$sb.Append("<div class='scroll'><table class='t sortable'><thead><tr><th>Risk</th><th>Device</th><th>Serial</th><th>User</th><th>Status</th><th>Recommended action</th><th>Encrypted</th><th>Last sync</th></tr></thead><tbody>")
foreach ($d in $atRisk) {
$sync = HE $d.LastSync
if ($d.IsStale -eq $true) { $sync = "<b style='color:#dc2626'>$sync</b>" }
$encTxt = 'No'; if ($d.IsEncrypted -eq $true) { $encTxt = 'Yes' }
[void]$sb.Append("<tr><td data-v='$($script:RiskOrder[$d.Risk])'>$(Get-Badge $d.Risk $d.Risk)</td><td><b>$(HE $d.DeviceName)</b></td><td class='mono'>$(HE $d.SerialNumber)</td><td>$(HE $d.PrimaryUser)</td><td>$(HE $d.Status)</td><td class='small'>$(HE $d.Recommendation)</td><td>$encTxt</td><td data-v='$(HE $d.LastSyncUtc)'>$sync</td></tr>")
}
[void]$sb.Append("</tbody></table></div>")
}
else { [void]$sb.Append("<p style='color:#166534;font-weight:600'>&#9989; Nothing to do: every device is protected.</p>") }
[void]$sb.Append("</div>")
# Breakdowns
[void]$sb.Append("<div class='grid2'>")
[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("</div>")
# Orphans
if (@($Orphans).Count -gt 0) {
[void]$sb.Append("<div class='card'><h2>&#128273; Recovery keys of devices not managed by Intune</h2><div class='sub'>$(@($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.</div><div class='scroll'><table class='t sortable'><thead><tr><th>Entra device name</th><th>Entra state</th><th>Entra device ID</th><th class='r'>Keys</th><th>Last key backup</th></tr></thead><tbody>")
foreach ($o in @($Orphans | Sort-Object -Property LastKeyBackup -Descending)) {
[void]$sb.Append("<tr><td>$(HE $o.EntraName)</td><td>$(HE $o.EntraState)</td><td class='mono'>$(HE $o.EntraDeviceId)</td><td class='r'>$($o.KeyCount)</td><td>$(HE $o.LastKeyBackup)</td></tr>")
}
[void]$sb.Append("</tbody></table></div></div>")
}
# Inventory
[void]$sb.Append("<div class='card'><h2>&#128203; Full inventory</h2><div class='sub'><span id='cnt'>$(@($Records).Count)</span> device(s) shown - search on any column, filter by risk, click a header to sort</div>")
[void]$sb.Append("<div class='toolbar'><input id='q' type='search' placeholder='Search device, serial, user, model, status...'/><button class='flt on' data-r='All'>All</button><button class='flt' data-r='Critical'>Critical</button><button class='flt' data-r='High'>High</button><button class='flt' data-r='Medium'>Medium</button><button class='flt' data-r='OK'>Protected</button><button class='flt' data-r='Stale'>Stale</button></div>")
[void]$sb.Append("<div class='scroll'><table id='inv' class='t sortable'><thead><tr><th>Risk</th><th>Device</th><th>Serial</th><th>User</th><th>Manufacturer / model</th><th>OS</th><th>Join</th><th>Compliance</th><th>Encrypted</th><th class='r'>Keys (OS)</th><th>Last key backup</th><th>Last sync</th><th>Status</th></tr></thead><tbody>")
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 = "<b style='color:#dc2626'>$sync</b>" }
$encTxt = 'No'; if ($d.IsEncrypted -eq $true) { $encTxt = 'Yes' }
$lbl = $d.Risk; if ($lbl -eq 'OK') { $lbl = 'Protected' }
[void]$sb.Append("<tr data-risk='$($d.Risk)' data-stale='$stale'><td data-v='$($script:RiskOrder[$d.Risk])'>$(Get-Badge $lbl $d.Risk)</td><td><b>$(HE $d.DeviceName)</b></td><td class='mono'>$(HE $d.SerialNumber)</td><td>$(HE $d.PrimaryUser)</td><td>$(HE $d.Manufacturer)<br/><span class='small'>$(HE $d.Model)</span></td><td class='mono'>$(HE $d.OSVersion)</td><td>$(HE $d.JoinType)</td><td>$(HE $d.ComplianceState)</td><td>$encTxt</td><td class='r' data-v='$($d.KeyCount)'>$($d.KeyCount) ($($d.OsVolumeKeyCount))</td><td data-v='$(HE $d.LastKeyBackupUtc)'>$(HE $d.LastKeyBackup)</td><td data-v='$(HE $d.LastSyncUtc)'>$sync</td><td class='small'>$(HE $d.Status)</td></tr>")
}
[void]$sb.Append("</tbody></table></div></div>")
# Legend
[void]$sb.Append("<div class='card'><h2>Legend &amp; method</h2><div class='sub'>How each device is classified</div><table class='t'><tbody>")
[void]$sb.Append("<tr><td>$(Get-Badge 'Critical' 'Critical')</td><td><b>Encrypted - NO key in Entra ID</b>: the disk is encrypted but no recovery key is escrowed. A recovery prompt (BIOS/TPM update, hardware change) would mean data loss.</td></tr>")
[void]$sb.Append("<tr><td>$(Get-Badge 'High' 'High')</td><td><b>Not encrypted - no key</b> (encryption policy not applied) or <b>No Entra device ID</b> (the device cannot escrow a key).</td></tr>")
[void]$sb.Append("<tr><td>$(Get-Badge 'Medium' 'Medium')</td><td><b>Key for data volume only</b> (OS volume key missing) or <b>key escrowed but Intune reports not encrypted</b> (suspended BitLocker or outdated report).</td></tr>")
[void]$sb.Append("<tr><td>$(Get-Badge 'Protected' 'OK')</td><td>Encrypted and at least one OS volume recovery key escrowed in Entra ID.</td></tr>")
[void]$sb.Append("<tr><td><b>Stale</b></td><td>No Intune sync for more than $($Ctx.StaleDays) days: candidate for retirement or out of production.</td></tr>")
[void]$sb.Append("<tr><td><b>Source</b></td><td>Intune managedDevices (Windows) + Entra ID BitLocker recovery key metadata (ID, date, volume type). Recovery key values are never read nor exported.</td></tr>")
[void]$sb.Append("</tbody></table></div>")
[void]$sb.Append("<footer>BitLocker Key Escrow Monitor v$($Ctx.Version) &middot; $(HE $Ctx.RunEnv) &middot; generated $(HE $Ctx.GeneratedLocal)</footer></div><script>$js</script></body></html>")
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 eq '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 }

Was this article helpful?

🎯
MSEndpoint Academy · MD-102

Assess Your Microsoft 365 & Intune Skills (MD-102)

100% Free • 10 Real Questions

Applying this guide in production? Test your technical readiness against real exam scenarios from Microsoft 365 Certified: Endpoint Administrator (MD-102).

💡 MD-102 Express Knowledge Check Question 1 of 10

You want an Intune compliance policy assigned to All Devices to apply ONLY to corporate Windows 11 laptops without waiting for dynamic group re-evaluation. Which Intune capability handles this instantaneously at check-in?

🔒 100% Free • 📊 Instant Explanations • 🖥️ Pearson VUE Mode
Take Free 10-Question MD-102 Diagnostic → MD-102 2026 Exam Guide & Sample Q&A Launch Pearson VUE Simulator
🎁 Free Community Automation Hub

Functional Automation & Blueprints

Production-ready scripts, GitHub repositories, and architectural blueprints created for this technical guide.

PowerShell 5.1 / 7.x, Microsoft Graph REST API, Azure Automation Managed Identity, Azure Blob Storage, Intune, Entra ID
AUTOMATION TOOLKIT

BitLocker Key Escrow Monitor (Azure Automation Runbook)

Tenant-scale PowerShell 5.1/7.x Azure Automation runbook to inventory Intune Windows devices, bulk-audit Entra ID BitLocker key metadata, diff Azure Storage snapshots, export RSA-OAEP + AES-256 encrypted recovery key backups, and email Outlook + interactive HTML reports.

Community Repo Download .ps1

🎓 Ready to go deeper on MD-102?

Practice real MD-102 exam questions, study verified Microsoft Learn explanations, and test yourself in Pearson VUE simulator mode.

Free 10Q MD-102 Exam → Launch Simulator
📡

Don't miss the Friday Microsoft Endpoint & Security TV Digest

One email a week: the Intune, Entra & Windows changes that actually matter, the Alex & Sarah TV episode, and new production-ready PowerShell scripts. No spam, unsubscribe in one click.

Browse past TV episodes & issues →
Souhaiel Morhag
Souhaiel Morhag
Microsoft Endpoint & Modern Workplace Engineer

Souhaiel Morhag is a Microsoft Intune and endpoint management specialist with hands-on experience deploying and securing enterprise environments across Microsoft 365. He founded MSEndpoint.com to share practical, real-world guides for IT admins navigating Microsoft technologies — and built the MSEndpoint Academy at app.msendpoint.com/academy, a dedicated learning platform for professionals preparing for the MD-102 (Microsoft 365 Endpoint Administrator) certification. Through in-depth articles and AI-powered practice exams, Souhaiel helps IT teams move faster and certify with confidence.

Related Articles

Popular on MSEndpoint