Connect multiple SharePoint site collections with PnP PowerShell

Discover how to link multiple SharePoint site collections effortlessly in a single script with PnP PowerShell.

Introduction

PnP PowerShell is an open-source PowerShell module that provides an efficient way in managing Microsoft 365, SharePoint and Teams. With the help of collection of cmdlets, we can create an automation script and simplify complex administrative tasks.

Establishing Connection

To access the data from a SharePoint site, the connection to the site should be established first. This can be achieved using the Connect-PnPOnline cmdlet, which requires the site URL and authentication details to set up the connection.

Problem

In some of the automation scripts, there is a possibility to connect with multiple SharePoint sites. During that When we used Connect-PnPOnline always returns the connection reference of last connected site.

Solution

To handle multiple connection references, you can store them in a variable in two methods:

Approach 1:

Use the -RetunConnection parameter with Connect-PnPOnline to directly store the connection reference in a variable.

Ex:

$siteOneConnnection = Connect-PnPOnline -Url $siteOneURL -Interactive -ClientID $clientID -ReturnConnection

Approach 2:

Call Get-PnPConnection after executing Connect-PnPOnline to retrieve and store the connection reference
Ex:
Connect-PnPOnline -Url $siteTwoURL -Interactive -ClientID $clientID
$siteTwoConnection = Get-PnPConnection
Both approaches can be used within a single automation script. You can reference either connection at any point by passing -Connection parameter to other cmdlets to interact with the respective site.
Shantha Kumar
Shantha Kumar
Articles: 301