Public/Test-MgkTenantConnection.ps1

function Test-MgkTenantConnection {
    <#
    .SYNOPSIS
        Checks which tenants in a fleet are actually connectable right now.
    .DESCRIPTION
        Attempts a certificate app-only Connect-MgGraph plus a trivial Graph
        call per tenant and reports the outcome. Run this before a long sweep
        or on a schedule — it catches expired certificates, deleted app
        registrations and revoked consent before they ruin a real run.
    .PARAMETER Tenant
        Tenant config objects (from Get-MgkTenantConfig), by pipeline or parameter.
    .OUTPUTS
        One object per tenant: TenantName, Connectable, Detail.
    .EXAMPLE
        Get-MgkTenantConfig -Path tenants.json | Test-MgkTenantConnection
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [PSTypeName('MspGraphKit.TenantConfig')]
        [object[]]$Tenant
    )

    process {
        foreach ($t in $Tenant) {
            try {
                Connect-MgGraph -TenantId $t.TenantId -ClientId $t.ClientId `
                    -CertificateThumbprint $t.CertificateThumbprint -NoWelcome -ErrorAction Stop
                $org = (Invoke-MgGraphRequest -Method GET `
                    -Uri 'https://graph.microsoft.com/v1.0/organization?$select=displayName').value

                [pscustomobject]@{
                    TenantName  = $t.TenantName
                    Connectable = $true
                    Detail      = "OK — $($org.displayName)"
                }
            }
            catch {
                [pscustomobject]@{
                    TenantName  = $t.TenantName
                    Connectable = $false
                    Detail      = "$_"
                }
            }
            finally {
                Disconnect-MgGraph -ErrorAction SilentlyContinue | Out-Null
            }
        }
    }
}