-
Notifications
You must be signed in to change notification settings - Fork 247
SharePoint Online Connection Script
directorcia edited this page Dec 16, 2025
·
1 revision
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.
- 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).
- Windows PowerShell 7+ recommended; the script checks
$PSVersionTable. - Internet connectivity.
- Permissions to consent Graph scopes:
Domain.Read.AllandOrganization.Read.All. - Microsoft Graph modules installed locally (the script can install/update if permitted):
Microsoft.Graph.AuthenticationMicrosoft.Graph.Identity.DirectoryManagement
- SharePoint Online module:
Microsoft.Online.SharePoint.PowerShell(install/update prompted if missing).
-
-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.
- Clears host and logs mode (
DebugvsInfo). - Reports PowerShell version and prompt mode.
- Checks for
Microsoft.Graph.Identity.DirectoryManagementand 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.
- "Assembly with same name is already loaded" for
- Logic:
- If
Microsoft.Graph.Authenticationassembly 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.
- If
- 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 ....
- Interactive:
- Device code UX:
- Opens
https://microsoft.com/devicelogin. - Prints the device code when detected.
- Opens
- On success: prints
AccountandTenantIdfromGet-MgContext.
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): ReadsVerifiedDomainsand picks the initial*.onmicrosoft.comdomain. - From REST Graph (
Invoke-MgGraphRequest): Calls/v1.0/organization(and, if needed,/v1.0/domains) to locate the initialonmicrosoft.comdomain. - Manual fallback: If auto methods fail and
-nopromptis not set, prompts for the tenant name (the part before.onmicrosoft.com).
Constructed output:
- SPO Admin URL:
https://<tenant>-admin.sharepoint.com
- Checks
Microsoft.Online.SharePoint.PowerShellpresence. - Offers installation/update with admin elevation if required.
- Informational lines prefixed with
[Info], warnings in yellow, errors in red. - Transcript file when
-debugis set. - Final output includes: Graph connection status, account, tenant id, derived SPO admin URL, and module checks.
- Symptom:
Unable to load Microsoft Graph PowerShell modulewithAssembly ... 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.
- The script clears loaded
- Symptom:
InteractiveBrowserCredential authentication failedwith localhost listener error. - Mitigation:
- Use device code flow (
-UseDeviceCode). - Or run
netsh http add iplisten 127.0.0.1from elevated prompt if localhost listener issues persist.
- Use device code flow (
- 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.Allis included in scopes.
- Disconnect stale sessions:
- If REST or cmdlet queries fail, the script will prompt for manual entry unless
-nopromptis set. - Verify your account has permissions to read organization and domain properties.
# Interactive login, checks for updates, prompts as needed
.\o365-connect-spo.ps1# No prompts, no updates (fails if tenant cannot be auto-detected)
.\o365-connect-spo.ps1 -noprompt -noupdate.\o365-connect-spo.ps1 -UseDeviceCodeDisconnect-MgGraph
.\o365-connect-spo.ps1 -noupdate- 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.comandlogin.microsoftonline.comare reachable. - Run elevated when installing or updating modules.
- 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.
- 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.