Private/Get-NSPConditionalAccessHomeCountryEntry.ps1

function Get-NSPConditionalAccessHomeCountryEntry {
    <#
    .SYNOPSIS
        Reads permanent group-specific home countries without changing the tenant-wide default.
    #>

    [CmdletBinding()]
    param([Parameter(Mandatory)]$TenantProfile)
    $entries = Get-NSPConditionalAccessMapValue $TenantProfile 'HomeCountryGroups'
    if ($null -eq $entries) { return }
    $keys = if ($entries -is [System.Collections.IDictionary]) { @($entries.Keys) } else { @($entries.PSObject.Properties.Name) }
    $seen = @{}
    $travelIds = @(Get-NSPConditionalAccessTravelEntry $TenantProfile | ForEach-Object { $_.Ids })
    foreach ($key in @($keys | Sort-Object)) {
        if ($key -notmatch '^\d{2}$') { throw "Home country group key '$key' must be two digits." }
        $entry = Get-NSPConditionalAccessMapValue $entries $key
        $countries = @(Get-NSPConditionalAccessMapValue $entry 'Countries' | Where-Object { $_ })
        $ids = @(Get-NSPConditionalAccessMapValue $entry 'Ids' | Where-Object { $_ })
        if (-not $countries.Count -or -not $ids.Count) { throw "Home country group '$key' needs countries and bound group IDs." }
        foreach ($country in $countries) {
            if ($country -cnotmatch '^[A-Z]{2}$') { throw "Home country group '$key' has an invalid country code." }
        }
        if (@($ids | Where-Object { $_ -in $travelIds }).Count) { throw 'Home and travel entries must use separate directory groups; otherwise a home policy could exempt its own members.' }
        $retiring = [bool](Get-NSPConditionalAccessMapValue $entry 'RetireRequested')
        if (-not $retiring) {
            foreach ($id in $ids) {
                if ($seen.ContainsKey([string]$id)) { throw "A group is bound to more than one active home country entry ($($seen[[string]$id]), $key)." }
                $seen[[string]$id] = $key
            }
        }
        [pscustomobject]@{
            Key = [string]$key
            Name = Get-NSPConditionalAccessMapValue $entry 'Name'
            Countries = $countries
            Ids = $ids
            Labels = @(Get-NSPConditionalAccessMapValue $entry 'Labels')
            Status = if ($retiring) { 'RetireRequested' } else { 'Active' }
            PolicyId = "NSP-HOME-GEO-$key"
            DefaultName = Get-NSPConditionalAccessMapValue $entry 'Name'
            EndDate = $null
        }
    }
}