Private/Connect-SPMSite.ps1

function Connect-SPMSite {
    <#
    .SYNOPSIS
        Connects to a SharePoint site using the auth options collected by Invoke-SPPermissionScan.
    .DESCRIPTION
        With -ClientId a new connection is established (certificate app-only or interactive;
        interactive re-connects are silent thanks to the MSAL token cache). Without -ClientId
        an existing PnP connection to the same URL is reused.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Url,

        [Parameter(Mandatory)]
        [hashtable]$Auth
    )

    if ($Auth.ClientId) {
        $params = @{ Url = $Url; ClientId = $Auth.ClientId }
        if ($Auth.Tenant) { $params.Tenant = $Auth.Tenant }
        if ($Auth.CertificatePath) {
            $params.CertificatePath = $Auth.CertificatePath
            if ($Auth.CertificatePassword) { $params.CertificatePassword = $Auth.CertificatePassword }
        }
        elseif ($Auth.Thumbprint) {
            $params.Thumbprint = $Auth.Thumbprint
        }
        elseif ($Auth.Interactive) {
            $params.Interactive = $true
        }
        else {
            throw '-ClientId requires one of -CertificatePath, -Thumbprint or -Interactive.'
        }
        Invoke-SPMWithRetry { Connect-PnPOnline @params }
        return
    }

    $existing = $null
    try { $existing = Get-PnPConnection } catch { $existing = $null }
    if ($existing -and $existing.Url -and ($existing.Url.TrimEnd('/') -eq $Url.TrimEnd('/'))) {
        return
    }

    throw "No matching PnP connection for '$Url'. Either pass -ClientId (with a certificate or -Interactive) or run Connect-PnPOnline -Url '$Url' first."
}