Private/SID/Test-OrphanedSID.ps1

#Requires -Version 5.1

# The cache of lookup results, created when this file is loaded. The module loads the file once
# for each import, so the cache lives as long as the module does: a second run in the same
# PowerShell session reuses it. The assignments are unconditional because the root module sets
# strict mode, and a test of a variable that was never assigned is an error there (#153).
$script:SIDValidationCache = @{}
# Lookup counters feed CacheHitRatio in Get-SIDValidationCacheStat
$script:SIDValidationCacheLookups = 0
$script:SIDValidationCacheHits = 0
# Set while the directory server is known to be unreachable (#82): the time it was first found
# so, and the time from which a directory lookup is tried again. Unlike the cache they are per
# run, and Start-OrphanedSidSession resets them.
$script:DirectoryUnreachableSince = $null
$script:DirectoryRetryAt = $null

function Test-OrphanedSID {
    <#
    .SYNOPSIS
        Tests whether a SID is orphaned (no longer exists in Active Directory)

    .DESCRIPTION
        Performs comprehensive testing to determine if a SID is orphaned by checking
        multiple AD lookup methods and utilizing caching for performance. This function
        is essential for identifying SIDs that should be removed from ACLs during
        security cleanup operations.

        OUTCOMES:
        - Orphaned: every lookup completed and none found the SID, or it was found only
          among deleted objects
        - Exists: a lookup found a live principal with the SID
        - Unverified: nothing found the SID, but at least one lookup failed for a reason
          other than "not found" (timeout, access denied, unreachable domain controller).
          ErrorMessage names each failure. Unverified SIDs are never removed and are not
          cached, so a later call performs the lookups again.

        UNREACHABLE DIRECTORY SERVER:
        Each directory lookup against a server that does not answer waits for the AD Web
        Services connect timeout, about 42 seconds. Once one lookup fails with
        ADServerDownException, the remaining directory lookups for this SID would fail the
        same way, so they are skipped and listed in ErrorMessage as skipped. The SID is
        Unverified, exactly as if each had been tried. SecurityIdentifier.Translate still runs:
        it goes through LSA rather than AD Web Services, and a name it returns proves the SID
        exists.

        The SIDs that follow would each wait out the same timeout, for the same reason. So for
        60 seconds after a lookup found the server unreachable, no directory lookup is attempted
        for any SID: each such SID is Unverified, with all five lookups listed as not attempted,
        and is not cached. The first SID after that time tries the directory again. If the
        server answers, lookups go on as usual; if not, another 60 seconds begin. One warning in
        the log says that the server cannot be contacted, and one information entry says when
        it answers again. See Register-DirectoryLookupOutcome.

        TECHNICAL FEATURES:
        - Multiple validation methods (Get-ADObject, SecurityIdentifier translation, type-specific lookups)
        - Performance caching to avoid repeated AD queries, in $script:SIDValidationCache
        - Handles deleted objects and various object types
        - Comprehensive error handling with correlation tracking
        - Integration with retry logic for AD operations

    .PARAMETER SID
        [String] (Mandatory: Yes, Pipeline: ByValue)

        The Security Identifier to test for orphaned status.

        VALIDATION RULES:
        - Cannot be null or empty
        - A value that Test-SIDFormat does not accept gets the status Unverified, and no
          lookup is made

        EXAMPLES:
        - Domain user: "S-1-5-21-1234567890-1234567890-1234567890-1001"
        - Built-in account: "S-1-5-32-544"
        - Service SID: "S-1-5-80-123456789-123456789-123456789-123456789-123456789"

    .PARAMETER MaxRetries
        [Int] (Mandatory: No; 0-10, default 3)

        Retries after the first attempt for each directory lookup whose failure looks transient
        (a timeout, a busy or unavailable server). The public commands' -MaxRetries arrives here.
        A server that cannot be contacted is not retried; see UNREACHABLE DIRECTORY SERVER.

    .PARAMETER CorrelationId
        [String] (Mandatory: No)

        Correlation ID for tracking this operation across logs and troubleshooting.
        Defaults to auto-generated GUID if not provided.

    .EXAMPLE
        PS> Test-OrphanedSID -SID "S-1-5-21-1234567890-1234567890-1234567890-1001"

        DESCRIPTION: Basic orphaned SID test for domain user
        OUTPUT: SIDLookupResult whose Status is Orphaned, Exists or Unverified
        USE CASE: Security audit to identify unused ACL entries

    .EXAMPLE
        PS> @('S-1-5-21-123-456-789-1001', 'S-1-5-32-544') | Test-OrphanedSID

        DESCRIPTION: Pipeline processing of multiple SIDs
        OUTPUT: One SIDLookupResult for each SID
        USE CASE: Bulk validation during ACL cleanup operations

    .EXAMPLE
        PS> $lookup = Test-OrphanedSID -SID "S-1-5-21-123-456-789-1001" -CorrelationId $correlationId
        PS> if ($lookup.Status -eq 'Unverified') { $lookup.ErrorMessage }

        DESCRIPTION: Orphaned test with correlation tracking, reading why a SID could not be verified
        OUTPUT: The lookup failures, such as an unreachable domain controller
        USE CASE: Enterprise audit operations requiring full traceability

    .INPUTS
        [String] - SID string values via pipeline

    .OUTPUTS
        [SIDLookupResult] - PSCustomObject with SID, Status (Orphaned, Exists, Unverified),
        IsOrphaned and ErrorMessage

    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/

        TROUBLESHOOTING:
        - For validation errors: .\Troubleshooting\Security\Orphaned-SID-Issues.md

    .LINK
        Test-SIDFormat
        Clear-SIDValidationCache
        Get-SIDValidationCacheStat
        .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    [OutputType('SIDLookupResult')]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [string]$SID,

        [Parameter()]
        [ValidateRange(0, 10)]
        [int]$MaxRetries = 3,

        [Parameter()]
        [string]$CorrelationId = [System.Guid]::NewGuid().ToString()
    )

    begin {
        # Initialize cache if it doesn't exist
        if (-not $script:SIDValidationCache) {
            $script:SIDValidationCache = @{}
        }
    }

    process {
        # A lookup that throws anything other than "not found" proves nothing about the SID. Each such
        # failure is collected here; with any present, the SID is Unverified rather than Orphaned.
        $lookupFailures = [System.Collections.Generic.List[string]]::new()
        # Once a directory lookup finds the server unreachable, the rest would wait out the same ~42 s
        # connect timeout and fail the same way (#82). They are skipped and named in the failure text.
        $serverDown = $false
        # Invoke-ADOperationWithRetry counts attempts, the first included
        $lookupAttempts = $MaxRetries + 1
        $skippedLookups = [System.Collections.Generic.List[string]]::new()

        try {
            Write-StructuredLog "Testing SID for orphaned status: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId

            # Validate SID format first using Test-SIDFormat module
            if (-not (Test-SIDFormat -SID $SID -CorrelationId $CorrelationId)) {
                Write-StructuredLog "SID format invalid - cannot be verified: $SID" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                return New-SIDLookupResult -SID $SID -Status 'Unverified' -ErrorMessage 'The SID is not in a valid format, so no lookup was made'
            }

            # Check cache first for performance. Only Orphaned and Exists are ever cached.
            $script:SIDValidationCacheLookups++
            if ($script:SIDValidationCache.ContainsKey($SID)) {
                $script:SIDValidationCacheHits++
                Write-StructuredLog "SID validation cache hit for $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                return $script:SIDValidationCache[$SID]
            }

            # An earlier SID of this run found the directory server unreachable, and the time to
            # try it again has not come (#82). The lookups below would each wait out the same
            # connect timeout, so none is attempted for this SID. The local name lookup still runs.
            $lookupsSuspended = $null -ne $script:DirectoryRetryAt -and (Get-Date) -lt $script:DirectoryRetryAt

            # Method 1: Try Get-ADObject with SID (most reliable)
            if ($lookupsSuspended) {
                $serverDown = $true
                $skippedLookups.Add('Get-ADObject')
            } else {
                try {
                    $adObject = Invoke-ADOperationWithRetry -ScriptBlock {
                        Get-ADObject -Filter "objectSid -eq '$SID'" -ErrorAction Stop
                    } -MaxRetries $lookupAttempts -OperationName 'Get-ADObject-BySID' -ObjectContext $SID -CorrelationId $CorrelationId

                    # The server answered. After a time in which it could not be contacted, this is
                    # the lookup that tried it again.
                    if ($null -ne $script:DirectoryUnreachableSince) {
                        Register-DirectoryLookupOutcome -Outcome Answered -CorrelationId $CorrelationId
                    }

                    if ($adObject) {
                        Write-StructuredLog "SID found in AD via Get-ADObject: $($adObject.DistinguishedName)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                        $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                        return $script:SIDValidationCache[$SID]
                    }
                }
                catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                    # Not found is an answer too
                    if ($null -ne $script:DirectoryUnreachableSince) {
                        Register-DirectoryLookupOutcome -Outcome Answered -CorrelationId $CorrelationId
                    }
                    Write-StructuredLog "SID not found via Get-ADObject: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
                catch {
                    $lookupFailures.Add("Get-ADObject: $($_.Exception.Message)")
                    if (Test-ADServerDownError -ErrorRecord $_) {
                        $serverDown = $true
                        Register-DirectoryLookupOutcome -Outcome Unreachable -CorrelationId $CorrelationId
                    }
                    Write-StructuredLog "Get-ADObject lookup failed for SID $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
            }

            # Method 1a: Check for deleted objects specifically. -IncludeDeletedObjects returns live
            # objects as well as tombstones, so this step is reached with a live match whenever
            # Method 1 failed rather than came back empty; isDeleted tells the two apart.
            if ($serverDown) {
                $skippedLookups.Add('Get-ADObject -IncludeDeletedObjects')
            } else {
                try {
                    $matchedObjects = @(Invoke-ADOperationWithRetry -ScriptBlock {
                            Get-ADObject -Filter "objectSid -eq '$SID'" -IncludeDeletedObjects -Properties isDeleted -ErrorAction Stop
                        } -MaxRetries $lookupAttempts -OperationName 'Get-ADObject-Deleted-BySID' -ObjectContext $SID -CorrelationId $CorrelationId)

                    $liveObject = $matchedObjects | Where-Object { $_ -and $_.isDeleted -ne $true } | Select-Object -First 1
                    $deletedObject = $matchedObjects | Where-Object { $_ -and $_.isDeleted -eq $true } | Select-Object -First 1

                    if ($liveObject) {
                        Write-StructuredLog "SID found as a live object by the deleted-objects lookup: $($liveObject.DistinguishedName)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                        $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                        return $script:SIDValidationCache[$SID]
                    }

                    if ($deletedObject) {
                        # A tombstone is positive evidence of deletion, so it settles the question even when
                        # an earlier lookup failed
                        Write-StructuredLog "SID found in deleted objects: $($deletedObject.DistinguishedName) - treating as orphaned" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                        $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Orphaned'
                        return $script:SIDValidationCache[$SID]
                    }
                }
                catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                    Write-StructuredLog "SID not found in deleted objects: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
                catch {
                    $lookupFailures.Add("Get-ADObject -IncludeDeletedObjects: $($_.Exception.Message)")
                    if (Test-ADServerDownError -ErrorRecord $_) {
                        $serverDown = $true
                        Register-DirectoryLookupOutcome -Outcome Unreachable -CorrelationId $CorrelationId
                    }
                    Write-StructuredLog "Deleted objects lookup failed for SID $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
            }

            # Method 2: Try direct SecurityIdentifier translation
            try {
                $securityIdentifier = [System.Security.Principal.SecurityIdentifier]::new($SID)
                $ntAccount = $securityIdentifier.Translate([System.Security.Principal.NTAccount])

                if ($ntAccount -and $ntAccount.Value -and -not $ntAccount.Value.StartsWith('S-1-')) {
                    Write-StructuredLog "SID successfully translated to account name: $($ntAccount.Value)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                    $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                    return $script:SIDValidationCache[$SID]
                }
            }
            catch [System.Security.Principal.IdentityNotMappedException] {
                Write-StructuredLog "SID could not be translated - likely orphaned: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
            }
            catch {
                $lookupFailures.Add("SecurityIdentifier.Translate: $($_.Exception.Message)")
                Write-StructuredLog "SecurityIdentifier translation failed for $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
            }

            # Method 3: Try specific object type lookups
            $objectTypes = @(
                @{ CmdLet = 'Get-ADUser'; Filter = "SID -eq '$SID'" },
                @{ CmdLet = 'Get-ADGroup'; Filter = "SID -eq '$SID'" },
                @{ CmdLet = 'Get-ADComputer'; Filter = "SID -eq '$SID'" }
            )

            foreach ($objectType in $objectTypes) {
                if ($serverDown) {
                    $skippedLookups.Add($objectType.CmdLet)
                    continue
                }
                try {
                    $result = Invoke-ADOperationWithRetry -ScriptBlock {
                        & $objectType.CmdLet -Filter $objectType.Filter -ErrorAction Stop
                    } -MaxRetries $lookupAttempts -OperationName $objectType.CmdLet -ObjectContext $SID -CorrelationId $CorrelationId

                    if ($result) {
                        Write-StructuredLog "SID found via $($objectType.CmdLet): $($result.DistinguishedName)" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
                        $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Exists'
                        return $script:SIDValidationCache[$SID]
                    }
                }
                catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
                    # Expected for orphaned SIDs, continue to next type
                    continue
                }
                catch {
                    $lookupFailures.Add("$($objectType.CmdLet): $($_.Exception.Message)")
                    if (Test-ADServerDownError -ErrorRecord $_) {
                        $serverDown = $true
                        Register-DirectoryLookupOutcome -Outcome Unreachable -CorrelationId $CorrelationId
                    }
                    Write-StructuredLog "$($objectType.CmdLet) lookup failed for $SID : $($_.Exception.Message)" -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
                }
            }

            # Nothing found the SID, but a lookup that failed might have. Unverified is not cached, so
            # a transient failure does not decide the answer for every later object in the run.
            if ($lookupFailures.Count -gt 0 -or $skippedLookups.Count -gt 0) {
                $countText = "$($lookupFailures.Count) lookup(s) failed"
                if ($skippedLookups.Count -gt 0) {
                    $countText += ", $($skippedLookups.Count) not attempted"
                    $lookupFailures.Add("Not attempted because the directory server could not be contacted: $($skippedLookups -join ', ')")
                }
                $failureText = $lookupFailures -join '; '
                # A SID whose lookups were not attempted at all says nothing new: the one warning
                # that the server cannot be contacted was written when that was found (#82)
                $unverifiedLevel = 'Warning'
                if ($lookupsSuspended) {
                    $unverifiedLevel = 'Debug'
                }
                Write-StructuredLog "SID could not be verified - $($countText): $SID ($failureText)" -Level $unverifiedLevel -Component 'SIDDetection' -CorrelationId $CorrelationId
                return New-SIDLookupResult -SID $SID -Status 'Unverified' -ErrorMessage $failureText
            }

            # Every lookup completed and none found the SID
            Write-StructuredLog "SID could not be resolved - marking as orphaned: $SID" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
            $script:SIDValidationCache[$SID] = New-SIDLookupResult -SID $SID -Status 'Orphaned'
            return $script:SIDValidationCache[$SID]

        }
        catch {
            # An unexpected failure proves nothing about the SID. Reporting it orphaned would put a live
            # principal's access in the removal path, so it is Unverified and is not cached.
            Write-StructuredLog "Error testing SID for orphaned status $SID : $($_.Exception.Message)" -Level Error -Component 'SIDDetection' -CorrelationId $CorrelationId
            return New-SIDLookupResult -SID $SID -Status 'Unverified' -ErrorMessage $_.Exception.Message
        }
    }
}


function New-SIDLookupResult {
    <#
    .SYNOPSIS
        Creates the result Test-OrphanedSID returns for one SID

    .DESCRIPTION
        Private factory for the three outcomes of an orphaned-SID check:

        - Orphaned: every lookup completed and none found the SID, or the SID was found only among
          deleted objects. Safe to report and to remove.
        - Exists: a lookup found a live principal with the SID.
        - Unverified: no lookup found the SID, but at least one failed for a reason other than
          "not found" (timeout, access denied, unreachable domain controller), so the SID may still
          belong to a live principal. Reported for re-checking, never removed.

    .PARAMETER SID
        The SID string that was tested.

    .PARAMETER Status
        Orphaned, Exists or Unverified.

    .PARAMETER ErrorMessage
        For Unverified, the failures that prevented a verdict. Empty otherwise.

    .OUTPUTS
        [PSCustomObject] with PSTypeName SIDLookupResult and properties SID, Status, IsOrphaned and
        ErrorMessage.

    .NOTES
        TROUBLESHOOTING:
        - For unverified SIDs: .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    [OutputType('SIDLookupResult')]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '',
        Justification = 'Factory function: builds an object and changes no state')]
    param(
        [Parameter(Mandatory)]
        [string]$SID,

        [Parameter(Mandatory)]
        [ValidateSet('Orphaned', 'Exists', 'Unverified')]
        [string]$Status,

        [Parameter()]
        [string]$ErrorMessage
    )

    [PSCustomObject]@{
        PSTypeName   = 'SIDLookupResult'
        SID          = $SID
        Status       = $Status
        IsOrphaned   = ($Status -eq 'Orphaned')
        ErrorMessage = $ErrorMessage
    }
}


function Clear-SIDValidationCache {
    <#
    .SYNOPSIS
        Clears the SID validation cache to free memory and reset validation state

    .DESCRIPTION
        Removes all entries from the SID validation cache, which is used to store
        results of orphaned SID tests for performance optimization. This function
        is useful for freeing memory or forcing re-validation of SIDs.

        TECHNICAL FEATURES:
        - Safe cache clearing with null checking
        - A log line that says how many entries were cleared
        - No side effects on other operations

    .PARAMETER CorrelationId
        Correlation ID of the log entries of this call. One is generated when none is given.

    .EXAMPLE
        PS> Clear-SIDValidationCache

        DESCRIPTION: Clear all cached SID validation results
        OUTPUT: Verbose message showing entries cleared
        USE CASE: Memory management during large operations

    .EXAMPLE
        PS> Clear-SIDValidationCache; Test-OrphanedSID -SID $sid

        DESCRIPTION: Force fresh validation by clearing cache first
        OUTPUT: Cache cleared, then fresh SID validation
        USE CASE: Troubleshooting when cached results may be stale

    .INPUTS
        None

    .OUTPUTS
        None (cache clearing operation)

    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/

        TROUBLESHOOTING:
        - For cache issues: .\Troubleshooting\Security\Orphaned-SID-Issues.md
        - For memory problems: .\Troubleshooting\Performance\Memory-Management-Issues.md

    .LINK
        Get-SIDValidationCacheStat
        Test-OrphanedSID
        .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    param(
        [Parameter()]
        [string]$CorrelationId = [System.Guid]::NewGuid().ToString()
    )

    if ($script:SIDValidationCache) {
        $count = $script:SIDValidationCache.Count
        $script:SIDValidationCache.Clear()
        $script:SIDValidationCacheLookups = 0
        $script:SIDValidationCacheHits = 0
        Write-StructuredLog "Cleared SID validation cache ($count entries)" -Level Information -Component 'SIDDetection' -CorrelationId $CorrelationId
    } else {
        Write-StructuredLog "SID validation cache was already empty" -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
    }
}


function Get-SIDValidationCacheStat {
    <#
    .SYNOPSIS
        Retrieves statistics about the current SID validation cache

    .DESCRIPTION
        Provides detailed statistics about the SID validation cache including
        total entries, orphaned SIDs count, and valid SIDs count. This function
        is useful for monitoring cache utilization and performance analysis.

        TECHNICAL FEATURES:
        - Safe statistics gathering with null checking
        - Detailed breakdown of cache contents
        - No impact on cache performance

    .EXAMPLE
        PS> Get-SIDValidationCacheStat

        DESCRIPTION: Get current cache statistics
        OUTPUT: Object with TotalEntries, OrphanedSIDs, ValidSIDs counts
        USE CASE: Performance monitoring during operations

    .EXAMPLE
        PS> $stats = Get-SIDValidationCacheStat; Write-Host "Cache efficiency: $($stats.ValidSIDs/$stats.TotalEntries*100)%"

        DESCRIPTION: Calculate cache efficiency ratio
        OUTPUT: Cache hit efficiency percentage
        USE CASE: Performance analysis and optimization

    .INPUTS
        None

    .OUTPUTS
        [PSCustomObject] with properties:
        - TotalEntries: Total number of cached SID validations
        - OrphanedSIDs: Number of SIDs identified as orphaned
        - ValidSIDs: Number of SIDs identified as valid
        - CacheHitRatio: Percentage of cache utilization

    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/

        TROUBLESHOOTING:
        - For cache analysis: .\Troubleshooting\Security\Orphaned-SID-Issues.md
        - For performance tuning: .\Troubleshooting\Performance\Performance-Tuning.md

    .LINK
        Clear-SIDValidationCache
        Test-OrphanedSID
        .\Troubleshooting\Security\Orphaned-SID-Issues.md
    #>

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    if ($script:SIDValidationCache) {
        $totalEntries = $script:SIDValidationCache.Count
        # The cache holds SIDLookupResult objects; Unverified results are never cached
        $orphanedCount = @($script:SIDValidationCache.Values | Where-Object { $_.Status -eq 'Orphaned' }).Count
        $validCount = @($script:SIDValidationCache.Values | Where-Object { $_.Status -eq 'Exists' }).Count

        return [PSCustomObject]@{
            PSTypeName = 'SIDValidationCacheStats'
            TotalEntries = $totalEntries
            OrphanedSIDs = $orphanedCount
            ValidSIDs = $validCount
            CacheHitRatio = if ($script:SIDValidationCacheLookups -gt 0) { [Math]::Round($script:SIDValidationCacheHits / $script:SIDValidationCacheLookups * 100, 2) } else { 0 }
            LastUpdated = Get-Date
        }
    }
    else {
        return [PSCustomObject]@{
            PSTypeName = 'SIDValidationCacheStats'
            TotalEntries = 0
            OrphanedSIDs = 0
            ValidSIDs = 0
            CacheHitRatio = 0
            LastUpdated = Get-Date
        }
    }
}

function Test-ADServerDownError {
    <#
    .SYNOPSIS
        Tells whether an error means the directory server could not be contacted.

    .DESCRIPTION
        Test-OrphanedSID runs up to five directory lookups for one SID. When the server that
        answers them is down, each waits for the AD Web Services connect timeout, about 42
        seconds, and fails with Microsoft.ActiveDirectory.Management.ADServerDownException
        ("Unable to contact the server"). This identifies that failure so the remaining lookups
        can be skipped.

        The exception chain is walked and compared by type name, so the function works when the
        ActiveDirectory module is not loaded and the type does not exist, as in unit tests.

    .PARAMETER ErrorRecord
        The error caught from a directory lookup.

    .OUTPUTS
        [bool] True when the error, or an exception inside it, is ADServerDownException.

    .EXAMPLE
        PS> try { Get-ADObject -Server dc01 -Filter * } catch { Test-ADServerDownError -ErrorRecord $_ }

        DESCRIPTION: Classifies a lookup failure
        OUTPUT: True when dc01 could not be contacted

    .NOTES
        Author: Jeffrey Stuhr
        Blog: https://www.techbyjeff.net
        LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/
    #>

    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.ErrorRecord]$ErrorRecord
    )

    $exception = $ErrorRecord.Exception
    while ($exception) {
        if ($exception.GetType().FullName -eq 'Microsoft.ActiveDirectory.Management.ADServerDownException') {
            return $true
        }
        $exception = $exception.InnerException
    }
    return $false
}


function Register-DirectoryLookupOutcome {
    <#
    .SYNOPSIS
    Records whether the directory server answered a lookup or could not be contacted.

    .DESCRIPTION
    Test-OrphanedSID calls this when a directory lookup fails because the server could not be
    contacted, and when its first lookup for a SID is answered after such a failure.

    For Unreachable it records the time, the first time only, and sets the time from which a
    lookup is tried again to 60 seconds from now. Until then Test-OrphanedSID attempts no
    directory lookup. The first call writes one warning to the log. A later call, made when the
    lookup that tried the server again failed as well, writes a debug entry.

    For Answered it clears both times and writes an information entry that says for how long
    the server could not be contacted. It does nothing when the server was not recorded as
    unreachable.

    The two times are module state of one run: Start-OrphanedSidSession resets them.

    .PARAMETER Outcome
    Unreachable when a lookup failed because the server could not be contacted. Answered when a
    lookup came back, with or without a result.

    .PARAMETER CorrelationId
    Correlation ID for the log entries.

    .EXAMPLE
    Register-DirectoryLookupOutcome -Outcome Unreachable -CorrelationId $CorrelationId

    Records that the server could not be contacted, and suspends directory lookups for 60 seconds.

    .EXAMPLE
    Register-DirectoryLookupOutcome -Outcome Answered -CorrelationId $CorrelationId

    Records that the server answers again, so that directory lookups are attempted for every SID.

    .INPUTS
    None.

    .OUTPUTS
    None.

    .NOTES
    AUTHOR:
    - Author: Jeffrey Stuhr
    - Blog: https://techbyjeff.net
    - LinkedIn: https://www.linkedin.com/in/jeffrey-stuhr-034214aa/
    - Bluesky: https://bsky.app/profile/techbyjeff.net
    #>

    [CmdletBinding()]
    [OutputType([void])]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('Answered', 'Unreachable')]
        [string]$Outcome,

        [Parameter()]
        [string]$CorrelationId
    )

    # A lookup against a server that does not answer waits about 42 seconds. A shorter time
    # than this would spend most of a run on such waits; a much longer one would leave a server
    # that came back unused for the rest of a short run.
    $retryAfterSeconds = 60
    $now = Get-Date

    if ($Outcome -eq 'Unreachable') {
        $isFirst = $null -eq $script:DirectoryUnreachableSince
        if ($isFirst) {
            $script:DirectoryUnreachableSince = $now
        }
        $script:DirectoryRetryAt = $now.AddSeconds($retryAfterSeconds)

        if ($isFirst) {
            $message = 'The directory server cannot be contacted. No directory lookup is attempted for the ' +
                "next $retryAfterSeconds seconds: a SID that needs one is reported as Unverified and is not " +
                'removed. The server is tried again after that.'
            Write-StructuredLog $message -Level Warning -Component 'SIDDetection' -CorrelationId $CorrelationId
        } else {
            $message = 'The directory server still cannot be contacted. ' +
                "It is tried again in $retryAfterSeconds seconds."
            Write-StructuredLog $message -Level Debug -Component 'SIDDetection' -CorrelationId $CorrelationId
        }
        return
    }

    if ($null -ne $script:DirectoryUnreachableSince) {
        $seconds = [int][math]::Round(($now - $script:DirectoryUnreachableSince).TotalSeconds)
        $script:DirectoryUnreachableSince = $null
        $script:DirectoryRetryAt = $null
        $message = "The directory server answers again, $seconds seconds after it could not be contacted. " +
            'Directory lookups are attempted again.'
        Write-StructuredLog $message -Level Information -Component 'SIDDetection' -CorrelationId $CorrelationId
    }
}