public/Connect-DcGraph.ps1

function Connect-DcGraph {
<#
.SYNOPSIS
    Connects to Microsoft Graph using certificate-based app auth or delegated scopes.

.PARAMETER TenantId
    Tenant (directory) ID (GUID).

.PARAMETER ClientId
    App registration (client) ID (GUID).

.PARAMETER CertificateThumbprint
    Certificate thumbprint for app auth.

.PARAMETER Scopes
    Delegated scopes if you prefer interactive auth.

.PARAMETER SkipIfConnected
    Do nothing if already connected.

.EXAMPLE
    Connect-DcGraph -TenantId ... -ClientId ... -CertificateThumbprint ...
#>

    [CmdletBinding()]
    param(
        [ValidatePattern('^[0-9a-fA-F-]{36}$')]
        [string]$TenantId,
        [ValidatePattern('^[0-9a-fA-F-]{36}$')]
        [string]$ClientId,
        [ValidatePattern('^[0-9A-Fa-f]{40}$')]
        [string]$CertificateThumbprint,
        [string[]]$Scopes,
        [switch]$SkipIfConnected
    )

    if ($SkipIfConnected) {
        try {
            $ctx = Get-MgContext -ErrorAction Stop
            if ($ctx) { return $ctx }
        } catch {}
    }

    if ($CertificateThumbprint -and $ClientId -and $TenantId) {
        Connect-MgGraph -TenantId $TenantId -ClientId $ClientId -CertificateThumbprint $CertificateThumbprint -NoWelcome -ErrorAction Stop
    }
    elseif ($Scopes) {
        Connect-MgGraph -Scopes $Scopes -NoWelcome -ErrorAction Stop
    }
    else {
        Connect-MgGraph -Scopes "Device.Read.All","DeviceManagementManagedDevices.ReadWrite.All","Directory.ReadWrite.All","DeviceManagementServiceConfig.Read.All" -NoWelcome -ErrorAction Stop
    }

    Get-MgContext
}