Private/Connect-SharePointService.ps1

# Connect-SharePointService.ps1
# Derives the SharePoint Admin URL from the tenant and populates $script:Context.
# Note: Actual SPO connection happens inside Get-SPOData.ps1 which runs in PS5.
# Part of the M365-QuickAssess module -- not exported.

function Connect-SharePointService
{
    Write-Log "Resolving SharePoint Admin URL..."

    try
    {
        $tenantName = ( Get-MgOrganization -ErrorAction Stop ).VerifiedDomains |
            Where-Object { $_.IsInitial -eq $true } |
            Select-Object -ExpandProperty Name

        if ( -not $tenantName )
        {
            throw "Could not resolve initial domain from tenant verified domains."
        }

        $tenantShortName = $tenantName.Split( "." )[0]
        $adminUrl        = "https://$tenantShortName-admin.sharepoint.com"

        $script:Context.SPOAdminUrl    = $adminUrl
        $script:Context.TenantShortName = $tenantShortName

        Write-Log "SharePoint Admin URL: $adminUrl"
    }
    catch
    {
        Write-Log "Failed to resolve SharePoint Admin URL: $( $_.Exception.Message )" "ERROR"
        throw
    }
}