Private/Baselines/Resolve-RepairedScopeTagId.ps1

function Resolve-RepairedScopeTagId {
    <#
    .SYNOPSIS
        Returns the scope tag IDs a policy should keep, or nothing when no repair is needed
    .DESCRIPTION
        Internal helper function. Drops scope tag IDs that do not exist in the tenant (and any IDs
        declared stale), keeps the rest, and falls back to the built-in Default scope tag (0) when
        nothing valid remains. The Default scope tag is never removed. A policy with no scope tags
        is not broken, so it needs no repair.
    .PARAMETER CurrentScopeTagId
        The policy's current roleScopeTagIds
    .PARAMETER TenantScopeTagId
        The scope tag IDs that exist in the tenant
    .PARAMETER StaleScopeTagId
        Scope tag IDs to remove even though they exist in the tenant
    #>

    [CmdletBinding()]
    [OutputType([string[]])]
    param(
        [Parameter()]
        [AllowNull()]
        [AllowEmptyCollection()]
        [object[]]$CurrentScopeTagId,

        [Parameter(Mandatory)]
        [string[]]$TenantScopeTagId,

        [Parameter()]
        [string[]]$StaleScopeTagId
    )

    $current = @($CurrentScopeTagId | Where-Object { $null -ne $_ } | ForEach-Object { [string]$_ })
    if ($current.Count -eq 0) {
        return $null
    }

    $kept = @($current | Where-Object {
            $_ -eq '0' -or ($_ -in $TenantScopeTagId -and $_ -notin $StaleScopeTagId)
        } | Select-Object -Unique)

    if ($kept.Count -eq $current.Count) {
        return $null
    }

    if ($kept.Count -eq 0) {
        return [string[]]@('0')
    }

    return [string[]]$kept
}