Skip to content

SharePoint Online Connection Script

directorcia edited this page Dec 16, 2025 · 1 revision

SharePoint Online Connection Script (o365-connect-spo.ps1)

This document explains the execution flow, operational logic, inputs, outputs, and troubleshooting guidance for o365-connect-spo.ps1. The script automates connecting to Microsoft 365 (Graph) and SharePoint Online (SPO) admin, verifies module prerequisites, and determines the tenant-specific SPO admin URL.

Overview

  • Validates PowerShell environment and writes colored status output.
  • Ensures required Microsoft Graph modules are present and loads them in a conflict-safe way.
  • Establishes a Microsoft Graph connection using interactive browser or device code, with smart fallback.
  • Determines your tenant name and constructs the SPO admin URL.
  • Ensures SharePoint Online PowerShell module availability (for subsequent SPO operations).

Prerequisites

  • Windows PowerShell 7+ recommended; the script checks $PSVersionTable.
  • Internet connectivity.
  • Permissions to consent Graph scopes: Domain.Read.All and Organization.Read.All.
  • Microsoft Graph modules installed locally (the script can install/update if permitted):
    • Microsoft.Graph.Authentication
    • Microsoft.Graph.Identity.DirectoryManagement
  • SharePoint Online module: Microsoft.Online.SharePoint.PowerShell (install/update prompted if missing).

Parameters

  • -noprompt: Suppresses interactive prompts for installs/updates and tenant input. Non-interactive runs will fail if user input is required.
  • -noupdate: Skips checking for newer module versions in the PowerShell Gallery.
  • -debug: Enables transcript logging to ..\o365-connect-spo.txt.
  • -UseDeviceCode: Forces device code authentication instead of interactive browser.

Execution Flow

1) Startup and Diagnostics

  • Clears host and logs mode (Debug vs Info).
  • Reports PowerShell version and prompt mode.

2) Microsoft Graph Module Handling

  • Checks for Microsoft.Graph.Identity.DirectoryManagement and reports install/update guidance.
  • Loads Graph modules using a version-lock strategy to avoid the common error:
    • "Assembly with same name is already loaded" for Microsoft.Graph.Authentication.
  • Logic:
    • If Microsoft.Graph.Authentication assembly is already in the AppDomain, lock to that exact version and import matching module paths.
    • Otherwise, remove any loaded Microsoft.Graph* modules, find the highest common version among required modules and import by explicit module path.
    • Falls back to latest available modules if no common version is found.

3) Microsoft Graph Authentication

  • Detects existing Graph context. If a stale context is present, disconnects (Disconnect-MgGraph) before reconnecting with required scopes.
  • Auth paths:
    • Interactive: Connect-MgGraph -Scopes "Domain.Read.All","Organization.Read.All" -NoWelcome.
    • Device code (forced or fallback): Connect-MgGraph -UseDeviceCode -Scopes ....
  • Device code UX:
    • Opens https://microsoft.com/devicelogin.
    • Prints the device code when detected.
  • On success: prints Account and TenantId from Get-MgContext.

4) Tenant Name Detection

The script uses multiple strategies in order:

  • From Get-MgContext.Account: If the account domain ends with *.onmicrosoft.com, the tenant is the subdomain.
  • From Get-MgOrganization (Graph cmdlet): Reads VerifiedDomains and picks the initial *.onmicrosoft.com domain.
  • From REST Graph (Invoke-MgGraphRequest): Calls /v1.0/organization (and, if needed, /v1.0/domains) to locate the initial onmicrosoft.com domain.
  • Manual fallback: If auto methods fail and -noprompt is not set, prompts for the tenant name (the part before .onmicrosoft.com).

Constructed output:

  • SPO Admin URL: https://<tenant>-admin.sharepoint.com

5) SharePoint Online Module

  • Checks Microsoft.Online.SharePoint.PowerShell presence.
  • Offers installation/update with admin elevation if required.

Common Outputs

  • Informational lines prefixed with [Info], warnings in yellow, errors in red.
  • Transcript file when -debug is set.
  • Final output includes: Graph connection status, account, tenant id, derived SPO admin URL, and module checks.

Error Handling & Troubleshooting

Graph Module Load Errors

  • Symptom: Unable to load Microsoft Graph PowerShell module with Assembly ... already loaded.
  • Mitigation:
    • The script clears loaded Microsoft.Graph* modules and re-imports modules by explicit path, locked to the loaded assembly version.
    • If persistent, restart the PowerShell session to clear assemblies.

Interactive Browser Auth Failure (HttpListenerException)

  • Symptom: InteractiveBrowserCredential authentication failed with localhost listener error.
  • Mitigation:
    • Use device code flow (-UseDeviceCode).
    • Or run netsh http add iplisten 127.0.0.1 from elevated prompt if localhost listener issues persist.

Device Code Flow Null Reference Errors

  • Symptom: DeviceCodeCredential authentication failed: Object reference not set to an instance of an object.
  • Mitigation:
    • Disconnect stale sessions: Disconnect-MgGraph.
    • Retry with -UseDeviceCode.
    • Ensure Organization.Read.All is included in scopes.

Tenant Detection Failures

  • If REST or cmdlet queries fail, the script will prompt for manual entry unless -noprompt is set.
  • Verify your account has permissions to read organization and domain properties.

Usage Examples

Standard Run

# Interactive login, checks for updates, prompts as needed
.\o365-connect-spo.ps1

Non-interactive / CI Mode

# No prompts, no updates (fails if tenant cannot be auto-detected)
.\o365-connect-spo.ps1 -noprompt -noupdate

Force Device Code Flow

.\o365-connect-spo.ps1 -UseDeviceCode

Reset Graph Auth Context

Disconnect-MgGraph
.\o365-connect-spo.ps1 -noupdate

Notes and Best Practices

  • Keep Microsoft Graph modules aligned to avoid version mismatches across submodules.
  • Prefer device code flow on locked-down or headless environments.
  • If operating behind strict proxies, ensure graph.microsoft.com and login.microsoftonline.com are reachable.
  • Run elevated when installing or updating modules.

What This Script Does NOT Do

  • It does not execute SPO administrative actions beyond discovering the admin URL and ensuring module presence.
  • It does not modify tenant configuration or grant permissions.

Maintenance

  • Periodically review installed module versions (Get-InstalledModule Microsoft.Graph*).
  • Update scopes as needed if future Graph endpoints require broader permissions.
  • If Microsoft updates module structure, revisit the version-lock import logic.

Clone this wiki locally