Skip to content

SharePoint Online PnP Connection Script

directorcia edited this page Aug 1, 2025 · 1 revision

Overview

The o365-connect-pnp.ps1 script provides a robust, automated solution for connecting to SharePoint Online using PnP PowerShell with modern authentication requirements. It includes advanced Microsoft Graph compatibility fixes, automatic Azure AD app registration, and comprehensive error handling.

✅ Key Features

  • Microsoft Graph v2.26 Compatibility Fix: Automatic detection and resolution of assembly loading issues
  • Modern PnP Authentication: Compliant with September 2024 PnP PowerShell requirements
  • Automatic Azure AD App Registration: Creates custom apps for interactive login
  • Existing App Support: Use pre-configured Azure AD apps with -ClientId parameter
  • Comprehensive Module Management: Automatic installation and updates of required modules
  • PowerShell 7+ Compatibility: Enhanced for modern PowerShell environments

Prerequisites

  1. PowerShell 7.0 or above (Required)
  2. Internet connection for module installation/updates
  3. Azure AD permissions to create app registrations (for automatic app creation)
  4. (Optional) Existing Azure AD app with SharePoint permissions

Parameters

Parameter Type Default Description
-prompt Switch $false Set to $true to prompt for user input during installations
-noupdate Switch $false Set to $true to skip module updates (faster execution)
-debug Switch $false Set to $true to create detailed log file
-ClientId String $null Specify existing Azure AD App Client ID for PnP connection

Usage Examples

Basic Connection (Creates New App)

.\o365-connect-pnp.ps1

Use Existing Azure AD App

.\o365-connect-pnp.ps1 -ClientId "12345678-1234-1234-1234-123456789012"

Interactive Mode with Logging

.\o365-connect-pnp.ps1 -prompt $true -debug $true

Fast Execution with Existing App

.\o365-connect-pnp.ps1 -noupdate -ClientId "your-app-id"

Development Mode (Full Logging, No Updates)

.\o365-connect-pnp.ps1 -debug $true -noupdate $true

Script Operation Flow

1. Initialization Phase

  • PowerShell Version Check: Validates PowerShell 7+ requirement
  • Parameter Display: Shows current configuration and ClientId status
  • Logging Setup: Creates transcript file if debug mode enabled

2. Microsoft Graph Compatibility Fix

The script performs comprehensive version compatibility checks:

Version Detection

  • Checks current Microsoft.Graph module version
  • Identifies problematic versions (especially v2.26.0)
  • Detects version mismatches between sub-modules

Automatic Remediation

  • v2.26.0 Detection: Automatically uninstalls and downgrades to stable v2.25.0
  • Version Mismatch Fix: Removes all Graph modules and reinstalls with synchronized versions
  • Compatibility Verification: Tests assembly loading and module imports

Supported Versions

  • v2.25.0: Stable and recommended
  • ⚠️ v2.26.0: Problematic - automatically fixed
  • v2.28.0+: Compatible newer versions
  • < v2.25.0: Upgraded to stable version

3. Module Installation and Updates

Required Modules

  1. Microsoft.Graph (v2.25.0 or compatible)
  2. Microsoft.Graph.Identity.DirectoryManagement
  3. Microsoft.Graph.Sites
  4. PnP.PowerShell

Update Process (if -noupdate not specified)

  • Compares local vs. gallery versions
  • Prompts for updates (if -prompt enabled)
  • Automatic updates (if -prompt disabled)

4. Microsoft Graph Connection

  • Connects with scopes: Sites.Read.All, sites.ReadWrite.All, Domain.Read.All
  • Establishes authentication context for tenant operations
  • Retrieves tenant domain information

5. SharePoint Site Discovery

  • Auto-detects SharePoint tenant URL
  • Retrieves all available SharePoint sites
  • Displays interactive site selection grid
  • Returns selected site URL for PnP connection

6. PnP PowerShell Connection

Option A: Existing Azure AD App (if -ClientId provided)

# Uses provided Client ID
connect-pnponline -url $siteUrl -Interactive -ClientId $ClientId

Troubleshooting for Existing Apps:

  • Verifies Client ID format
  • Checks SharePoint permissions
  • Validates redirect URI configuration
  • Confirms public client settings

Option B: Automatic App Registration (if no -ClientId)

# Creates new app automatically
$appRegistration = Register-PnPEntraIDAppForInteractiveLogin -ApplicationName $appName -Tenant $tenantDomain
connect-pnponline -url $siteUrl -Interactive -ClientId $newClientId

App Creation Process:

  1. Generates unique app name: CIAOPS-PnP-PowerShell-YYYYMMDD-HHMMSS
  2. Registers with tenant domain
  3. Configures appropriate permissions
  4. Returns Client ID for future use

Fallback Options

  • Direct interactive connection (legacy support)
  • Manual app registration guidance
  • Comprehensive error messaging

Error Handling and Troubleshooting

Common Issues and Solutions

1. Microsoft Graph Assembly Loading Error

Could not load type 'Microsoft.Graph.Authentication.AzureIdentityAccessTokenProvider'

Solution: Automatically detected and fixed by version compatibility check

2. PnP Authentication Failures

For Existing Apps:

  • Verify Client ID is correct
  • Check app has SharePoint permissions
  • Ensure redirect URI includes http://localhost
  • Confirm app is configured as public client

For New Apps:

  • Ensure Microsoft Graph connection is active
  • Verify tenant admin permissions
  • Check network connectivity

3. PowerShell Version Issues

This script requires PowerShell version 7 or above

Solution: Upgrade to PowerShell 7+ from https://github.com/PowerShell/PowerShell

Manual App Registration

If automatic app registration fails, follow these steps:

Option 1: Automated Registration

Register-PnPEntraIDAppForInteractiveLogin -ApplicationName 'CIAOPS-PnP-App' -Tenant yourdomain.onmicrosoft.com

Option 2: Azure Portal Registration

  1. Navigate to Azure Portal > Entra ID > App Registrations
  2. Click New Registration
  3. Name: CIAOPS PnP PowerShell
  4. Redirect URI: http://localhost (Public client/native)
  5. Copy the Application (client) ID
  6. Re-run script with: .\o365-connect-pnp.ps1 -ClientId <your-client-id>

Logging and Debugging

Debug Mode

When -debug $true is specified:

  • Creates transcript file: ../o365-connect-pnp.txt
  • Logs all script operations
  • Captures error details
  • Includes module version information

Log File Location

Parent directory of script location
Example: If script is in C:\Scripts\, log is in C:\o365-connect-pnp.txt

Security Considerations

Permissions Required

  • Microsoft Graph: Sites.Read.All, sites.ReadWrite.All, Domain.Read.All
  • Azure AD: Application registration permissions (for automatic app creation)
  • SharePoint: Site access permissions

App Registration Security

  • Apps are created with minimal required permissions
  • Public client configuration for interactive authentication
  • Unique naming prevents conflicts
  • Client IDs can be reused for consistent access

Performance Optimizations

Fast Execution Mode

.\o365-connect-pnp.ps1 -noupdate -ClientId "existing-app-id"
  • Skips module update checks
  • Uses existing app (no creation overhead)
  • Reduces execution time significantly

Module Caching

  • Modules are installed once per system
  • Version checks prevent unnecessary updates
  • Import operations are optimized

Integration with Other Scripts

Saving Client ID for Reuse

After first run, the script displays:

💡 TIP: Save this Client ID for future use with -ClientId parameter
Future usage: .\o365-connect-pnp.ps1 -ClientId 12345678-1234-1234-1234-123456789012

Environment Variables

You can set a default Client ID in your PowerShell profile:

$env:DEFAULT_PNP_CLIENT_ID = "your-client-id"

Automation Scripts

For unattended execution:

# Use existing app, no prompts, no updates
.\o365-connect-pnp.ps1 -ClientId $clientId -noupdate

Version History and Compatibility

Current Version Features

  • ✅ Microsoft Graph v2.26 compatibility fix
  • ✅ Modern PnP authentication support
  • ✅ Automatic Azure AD app registration
  • ✅ Existing app support via -ClientId parameter
  • ✅ Enhanced error handling and troubleshooting

Breaking Changes

  • September 2024: PnP PowerShell requires custom app registration
  • PowerShell 7+: Required for modern module compatibility

Best Practices

For Organizations

  1. Create Centralized Apps: Register organization-wide Azure AD apps
  2. Distribute Client IDs: Share approved Client IDs with users
  3. Monitor App Usage: Track app registrations and usage
  4. Security Reviews: Regularly audit app permissions

For Developers

  1. Use Existing Apps: Leverage -ClientId parameter for consistency
  2. Enable Debugging: Use -debug for troubleshooting
  3. Version Control: Include Client IDs in secure configuration
  4. Error Handling: Implement retry logic for automation

For End Users

  1. Save Client IDs: Note Client IDs for future use
  2. Update Regularly: Run without -noupdate periodically
  3. Use Fast Mode: Employ -noupdate with existing apps for speed
  4. Report Issues: Use debug logs for support requests

Support and Resources

Documentation Links

Community Resources


Script provided as is. Use at own risk. No guarantees or warranty provided.

Last updated: August 2025

Clone this wiki locally