```powershell
<#
.SYNOPSIS
    Validates common Windows 10 Secure Boot startup integrity conditions.

.DESCRIPTION
    This script performs non-destructive checks that help troubleshoot Secure Boot failures
    after firmware, disk, bootloader, or policy changes.

    It gathers:
      - OS and firmware boot mode indicators
      - Secure Boot status when available
      - BitLocker protection status when available
      - UEFI boot order-related information when available
      - Relevant boot configuration data for review

    The script does not disable Secure Boot, modify firmware settings, or repair boot files.
    Use the output to decide whether to repair, roll back, or re-enroll trust settings.

.NOTES
    - Run in an elevated PowerShell session for the best results.
    - Some checks may require Windows 10, UEFI firmware, and/or administrative privileges.
    - Designed to be safe for production troubleshooting.

.EXAMPLE
    .\Test-SecureBootStartupIntegrity.ps1

.EXAMPLE
    .\Test-SecureBootStartupIntegrity.ps1 -OutputPath .\secureboot-check.txt -Detailed
#>

[CmdletBinding()]
param(
    [string]$OutputPath,
    [switch]$Detailed,
    [switch]$AsJson
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Write-Section {
    param([string]$Title)
    Write-Host "`n=== $Title ===" -ForegroundColor Cyan
}

function Get-CommandAvailability {
    param([string]$Name)
    return [bool](Get-Command -Name $Name -ErrorAction SilentlyContinue)
}

function Safe-Run {
    param(
        [scriptblock]$ScriptBlock,
        [string]$Fallback = 'Unavailable'
    )

    try {
        return & $ScriptBlock
    }
    catch {
        return $Fallback
    }
}

$results = [ordered]@{
    Timestamp               = (Get-Date).ToString('s')
    ComputerName            = $env:COMPUTERNAME
    User                    = $env:USERNAME
    ElevatedSession         = $false
    OsCaption               = $null
    OsVersion               = $null
    BuildNumber             = $null
    BiosMode                = $null
    SecureBootEnabled       = $null
    SecureBootUEFI          = $null
    BitLockerStatus         = $null
    FirmwareVendor          = $null
    FirmwareVersion         = $null
    BootManagerPath         = $null
    BootConfigurationSummary = @()
    Notes                   = @()
}

# Detect elevation
try {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object Security.Principal.WindowsPrincipal($identity)
    $results.ElevatedSession = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
catch {
    $results.ElevatedSession = $false
}

Write-Section 'System Information'
try {
    $os = Get-CimInstance Win32_OperatingSystem
    $cs = Get-CimInstance Win32_ComputerSystem
    $bios = Get-CimInstance Win32_BIOS

    $results.OsCaption = $os.Caption
    $results.OsVersion = $os.Version
    $results.BuildNumber = $os.BuildNumber
    $results.FirmwareVendor = $bios.Manufacturer
    $results.FirmwareVersion = ($bios.SMBIOSBIOSVersion -join ' ')

    Write-Host ("OS: {0} {1} (Build {2})" -f $results.OsCaption, $results.OsVersion, $results.BuildNumber)
    Write-Host ("Manufacturer: {0}" -f $cs.Manufacturer)
    Write-Host ("Model: {0}" -f $cs.Model)
    Write-Host ("BIOS Vendor: {0}" -f $results.FirmwareVendor)
    Write-Host ("BIOS Version: {0}" -f $results.FirmwareVersion)
}
catch {
    $results.Notes += 'Unable to collect full system information.'
    Write-Warning 'Unable to collect full system information.'
}

Write-Section 'Boot Mode and Secure Boot'
if (Get-CommandAvailability -Name Confirm-SecureBootUEFI) {
    try {
        $results.SecureBootUEFI = $true
        $results.SecureBootEnabled = Confirm-SecureBootUEFI
        Write-Host ("Secure Boot Enabled: {0}" -f $results.SecureBootEnabled)
    }
    catch {
        $results.SecureBootUEFI = $false
        $results.SecureBootEnabled = $null
        $results.Notes += 'Secure Boot status could not be read from this session or firmware does not expose it.'
        Write-Warning 'Secure Boot status could not be read from this session or firmware does not expose it.'
    }
}
else {
    $results.Notes += 'Confirm-SecureBootUEFI is not available on this system.'
    Write-Warning 'Confirm-SecureBootUEFI is not available on this system.'
}

try {
    $firmware = Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control' -Name 'PEFirmwareType' -ErrorAction Stop
    $results.BiosMode = if ($firmware.PEFirmwareType -eq 2) { 'UEFI' } elseif ($firmware.PEFirmwareType -eq 1) { 'Legacy BIOS' } else { 'Unknown' }
    Write-Host ("Firmware Mode: {0}" -f $results.BiosMode)
}
catch {
    $results.BiosMode = 'Unknown'
    $results.Notes += 'Unable to determine firmware mode from registry.'
    Write-Warning 'Unable to determine firmware mode from registry.'
}

Write-Section 'BitLocker'
if (Get-CommandAvailability -Name Get-BitLockerVolume) {
    try {
        $volumes = Get-BitLockerVolume
        foreach ($volume in $volumes) {
            $entry = [ordered]@{
                MountPoint = $volume.MountPoint
                VolumeStatus = $volume.VolumeStatus
                ProtectionStatus = $volume.ProtectionStatus
                LockStatus = $volume.LockStatus
                EncryptionMethod = $volume.EncryptionMethod
            }
            $results.BitLockerStatus += $entry
            Write-Host ("{0}: Volume={1}, Protection={2}, Lock={3}, Encryption={4}" -f \
                $volume.MountPoint, $volume.VolumeStatus, $volume.ProtectionStatus, $volume.LockStatus, $volume.EncryptionMethod)
        }
    }
    catch {
        $results.Notes += 'BitLocker status could not be read.'
        Write-Warning 'BitLocker status could not be read.'
    }
}
else {
    $results.Notes += 'BitLocker cmdlets are not available.'
    Write-Warning 'BitLocker cmdlets are not available.'
}

Write-Section 'Boot Configuration'
$bootEntries = @()

if (Get-CommandAvailability -Name bcdedit) {
    $bcdOutput = Safe-Run -ScriptBlock { bcdedit /enum all } -Fallback $null
    if ($bcdOutput) {
        $results.BootConfigurationSummary = $bcdOutput
        $bootEntries = $bcdOutput | Select-String -Pattern 'identifier|device|path|description|default|timeout|firmware|resumeobject' -CaseSensitive:$false
        Write-Host 'Collected bcdedit output for review.'
    }
    else {
        $results.Notes += 'bcdedit output could not be collected.'
        Write-Warning 'bcdedit output could not be collected.'
    }
}
else {
    $results.Notes += 'bcdedit is not available.'
    Write-Warning 'bcdedit is not available.'
}

if ($Detailed) {
    Write-Section 'Detailed Review'
    Write-Host 'Checklist:'
    Write-Host ('- UEFI mode expected: {0}' -f ($results.BiosMode -eq 'UEFI'))
    Write-Host ('- Secure Boot read succeeded: {0}' -f ($null -ne $results.SecureBootEnabled))
    Write-Host ('- BitLocker status available: {0}' -f (($results.BitLockerStatus | Measure-Object).Count -gt 0))
    Write-Host ('- Boot configuration summary lines collected: {0}' -f ($results.BootConfigurationSummary.Count))
}

Write-Section 'Assessment'
$issues = New-Object System.Collections.Generic.List[string]

if ($results.BiosMode -eq 'Legacy BIOS') {
    $issues.Add('System is in legacy BIOS mode; Secure Boot requires UEFI.')
}

if ($results.SecureBootEnabled -eq $false) {
    $issues.Add('Secure Boot is disabled.')
}

if ($results.SecureBootEnabled -eq $null) {
    $issues.Add('Secure Boot state could not be confirmed.')
}

if (($results.BitLockerStatus | Measure-Object).Count -gt 0) {
    foreach ($volume in $results.BitLockerStatus) {
        if ($volume.MountPoint -eq 'C:' -and $volume.ProtectionStatus -ne 'On') {
            $issues.Add('System drive BitLocker protection is not On; review whether recovery prompts were expected after recent changes.')
        }
    }
}

if ($issues.Count -eq 0) {
    Write-Host 'No obvious startup integrity inconsistencies were detected by this read-only check.' -ForegroundColor Green
}
else {
    Write-Host 'Potential startup integrity concerns:' -ForegroundColor Yellow
    $issues | ForEach-Object { Write-Host ("- {0}" -f $_) }
}

$results.Notes += $issues.ToArray()

if ($AsJson) {
    $output = $results | ConvertTo-Json -Depth 6
}
else {
    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add('Windows 10 Secure Boot Startup Integrity Report')
    $lines.Add(('Timestamp: {0}' -f $results.Timestamp))
    $lines.Add(('Computer: {0}' -f $results.ComputerName))
    $lines.Add(('OS: {0} {1} (Build {2})' -f $results.OsCaption, $results.OsVersion, $results.BuildNumber))
    $lines.Add(('Firmware Mode: {0}' -f $results.BiosMode))
    $lines.Add(('Secure Boot Enabled: {0}' -f $results.SecureBootEnabled))
    $lines.Add(('Elevated Session: {0}' -f $results.ElevatedSession))
    $lines.Add('')
    $lines.Add('Notes:')
    foreach ($note in ($results.Notes | Select-Object -Unique)) {
        $lines.Add((' - {0}' -f $note))
    }
    $output = $lines -join [Environment]::NewLine
}

if ($OutputPath) {
    try {
        $parent = Split-Path -Path $OutputPath -Parent
        if ($parent -and -not (Test-Path -Path $parent)) {
            New-Item -ItemType Directory -Path $parent -Force | Out-Null
        }
        $output | Out-File -FilePath $OutputPath -Encoding utf8
        Write-Host ("`nReport written to: {0}" -f $OutputPath) -ForegroundColor Green
    }
    catch {
        Write-Warning ("Unable to write output file: {0}" -f $_.Exception.Message)
    }
}
else {
    Write-Host "`n$output"
}

<#
Operational guidance:
- If firmware mode is Legacy BIOS, plan a controlled conversion to UEFI before expecting Secure Boot.
- If Secure Boot is disabled, verify whether the change was intentional and documented.
- If BitLocker recovery appeared after a change, compare the timing with firmware or disk maintenance.
- If boot entries look inconsistent, repair only the affected boot chain component and revalidate.
#>
```