Public/Baselines/Repair-IntuneBaselineScopeTag.ps1

function Repair-IntuneBaselineScopeTag {
    <#
    .SYNOPSIS
        Repairs hydration kit Settings Catalog policies that reference a scope tag missing from the tenant
    .DESCRIPTION
        IntuneHydrationKit 1.4.1 and earlier imported the 80 CISv3 Edge L1 policies with the source
        tenant's scope tag ID (2). In a tenant without that tag the Intune admin center shows
        "Scope tag deleted". Updating the module does not repair them because existing policies are
        skipped on import.
 
        This command finds Settings Catalog policies created by the kit (hydration marker in the
        description) whose roleScopeTagIds reference an ID that does not exist in the tenant, removes
        the missing IDs, and falls back to the built-in Default scope tag (0) when no valid ID remains.
        Only roleScopeTagIds is changed; settings and assignments are untouched. Each change is read
        back and verified.
 
        A scope tag ID that exists in the tenant is left alone by default, because a deliberate tag
        cannot be told apart from a coincidental match. Use -StaleScopeTagId to remove specific
        existing IDs as well.
 
        Reading the tenant's scope tags requires the DeviceManagementRBAC.Read.All permission, which
        Connect-IntuneHydration does not request by default. Connect with it explicitly, for example:
 
        Connect-IntuneHydration -TenantId <tenant> -Interactive -Scopes 'DeviceManagementConfiguration.ReadWrite.All', 'DeviceManagementRBAC.Read.All'
    .PARAMETER PolicyId
        Limit the repair to these policy IDs. Explicitly listed policies are repaired even without the
        hydration marker.
    .PARAMETER StaleScopeTagId
        Scope tag IDs to remove even though they exist in the tenant. Use when the tenant has its own
        scope tag with the same ID as the one carried by the templates (2). The Default scope tag (0)
        is never removed.
    .PARAMETER IncludeUnmanaged
        Also repair Settings Catalog policies that do not carry the hydration marker.
    .EXAMPLE
        Repair-IntuneBaselineScopeTag -WhatIf
 
        Lists the policies that would be repaired without changing anything.
    .EXAMPLE
        Repair-IntuneBaselineScopeTag
 
        Repairs every hydration kit Settings Catalog policy that references a missing scope tag.
    .EXAMPLE
        Repair-IntuneBaselineScopeTag -StaleScopeTagId 2 -WhatIf
 
        Previews removing scope tag 2 from hydration kit policies in a tenant where a tag with ID 2 exists.
    .OUTPUTS
        PSCustomObject with Name, Id, Before, After, Status and Reason for each policy that needed repair.
        Status is Repaired, WouldRepair, Skipped or Failed.
    #>

    [CmdletBinding(SupportsShouldProcess)]
    [OutputType([PSCustomObject])]
    param(
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string[]]$PolicyId,

        [Parameter()]
        [ValidatePattern('^\d+$')]
        [string[]]$StaleScopeTagId,

        [Parameter()]
        [switch]$IncludeUnmanaged
    )

    $requiredScopeText = "'DeviceManagementConfiguration.ReadWrite.All', 'DeviceManagementRBAC.Read.All'"
    $context = Get-MgContext
    if (-not $context) {
        $errorRecord = [System.Management.Automation.ErrorRecord]::new(
            [System.Exception]::new("Not connected to Microsoft Graph. Run Connect-IntuneHydration -TenantId <tenant> -Interactive -Scopes $requiredScopeText first."),
            'NotConnected',
            [System.Management.Automation.ErrorCategory]::ConnectionError,
            $null
        )
        $PSCmdlet.ThrowTerminatingError($errorRecord)
    }

    # Pin the reconnect hint to the current tenant and cloud. Without them Connect-IntuneHydration
    # defaults to the home tenant and the Global cloud, and a retry would repair the wrong tenant.
    $reconnectTenant = if ([string]::IsNullOrWhiteSpace($context.TenantId)) { '<tenant>' } else { [string]$context.TenantId }
    $reconnectCommand = "Connect-IntuneHydration -TenantId $reconnectTenant -Interactive -Scopes $requiredScopeText"
    if (-not [string]::IsNullOrWhiteSpace($context.Environment) -and [string]$context.Environment -ne 'Global') {
        $reconnectCommand += " -Environment $($context.Environment)"
    }

    # Read the tenant's scope tags first: without a trustworthy list nothing may be repaired.
    try {
        $tenantScopeTagIds = Get-HydrationTenantScopeTagId
    } catch {
        $errorRecord = [System.Management.Automation.ErrorRecord]::new(
            [System.Exception]::new("Could not read the tenant's scope tags, so no policy was changed. This needs the DeviceManagementRBAC.Read.All permission; reconnect to the same tenant with: $reconnectCommand. Details: $(Get-GraphErrorMessage -ErrorRecord $_)", $_.Exception),
            'ScopeTagReadFailed',
            [System.Management.Automation.ErrorCategory]::PermissionDenied,
            $null
        )
        $PSCmdlet.ThrowTerminatingError($errorRecord)
    }

    $allPolicies = Get-GraphPagedResults -Uri 'beta/deviceManagement/configurationPolicies?$select=id,name,description,roleScopeTagIds'
    $policies = @($allPolicies | Where-Object {
            $null -ne $_ -and
            ($PolicyId.Count -eq 0 -or $_.id -in $PolicyId) -and
            ($IncludeUnmanaged -or $_.id -in $PolicyId -or (Test-HydrationKitObject -Description ([string]$_.description)))
        })

    if ($policies.Count -eq 0) {
        Write-Warning 'No matching Settings Catalog policies were found.'
        return
    }

    $repairCount = 0
    foreach ($policy in $policies) {
        $before = @($policy.roleScopeTagIds | Where-Object { $null -ne $_ } | ForEach-Object { [string]$_ })
        $after = Resolve-RepairedScopeTagId -CurrentScopeTagId $before -TenantScopeTagId $tenantScopeTagIds -StaleScopeTagId $StaleScopeTagId
        if ($null -eq $after) {
            continue
        }

        $repairCount++
        $result = [ordered]@{
            Name   = [string]$policy.name
            Id     = [string]$policy.id
            Before = $before -join ','
            After  = $after -join ','
            Status = 'Repaired'
            Reason = $null
        }

        if (-not $PSCmdlet.ShouldProcess($result.Name, "Set roleScopeTagIds from [$($result.Before)] to [$($result.After)]")) {
            $result.Status = if ($WhatIfPreference) { 'WouldRepair' } else { 'Skipped' }
            [PSCustomObject]$result
            continue
        }

        try {
            $policyUri = "beta/deviceManagement/configurationPolicies/$($result.Id)"
            $bodyJson = @{ roleScopeTagIds = @($after) } | ConvertTo-Json -Depth 5
            Invoke-MgGraphRequest -Method PATCH -Uri $policyUri -Body $bodyJson -ContentType 'application/json' -ErrorAction Stop | Out-Null

            $verified = Invoke-MgGraphRequest -Method GET -Uri "$policyUri`?`$select=id,roleScopeTagIds" -ErrorAction Stop
            $verifiedIds = @($verified.roleScopeTagIds | ForEach-Object { [string]$_ } | Sort-Object)
            if (($verifiedIds -join ',') -ne ((@($after) | Sort-Object) -join ',')) {
                throw "The policy reports roleScopeTagIds [$($verifiedIds -join ',')] after the update; expected [$($result.After)]."
            }
        } catch {
            $result.Status = 'Failed'
            $result.Reason = Get-GraphErrorMessage -ErrorRecord $_
        }

        [PSCustomObject]$result
    }

    if ($repairCount -eq 0) {
        Write-Information "Checked $($policies.Count) policies; none reference a missing scope tag." -InformationAction Continue
    }
}