Connecting to Multiple SharePoint Sites with a Single Authentication Prompt Using PnP PowerShell

 Context

Sometimes, you must perform some activities to multiple SharePoint sites using a script. You would probably be prompted to get connected to each site because of MFA

In my case, I needed to verify if someone was site owner on multiple sites.



Prerequisites

You will need SharePoint Admin permissions (you may have to elevate your privileges "PIM").
PowerShell and PnP.PowerShell module must be installed.

Code Sample

In this example, I'm checking if my Entra ID group is member of site Onwers.

$siteUrls = Import-Csv -Path $CsvPath
$tenantAdminUrl = "https://yourTenant-admin.sharepoint.com"
$tenantClientID = "567bf829-465a-ds5e-ad03-0af9f30o5619"
$loginName = "c:0t.c|tenant|$aadGroupId"
$tenantConnection = Connect-PnPOnline -Url $tenantAdminUrl -ClientId $tenantClientID -Interactive -ReturnConnection

foreach ($siteUrl in $siteUrls) { 

    #Connect to the site
    
    Connect-PnPOnline -Url $siteUrl -ClientId $tenantClientID -Interactive -Connection $tenantConnection

    # Get associated Owners group
    $ownersGroup = Get-PnPGroup -AssociatedOwnerGroup
        

    $isOwner = $ownersGroup.Users | Where-Object { $_.LoginName -eq $loginName }
    if ($isOwner) {
        Write-Host "Already in Owners of: $($siteUrl)"           
    }
    else {
        #Do that
    }
}
# Do forget to disconnect
Disconnect-PnPOnline -Connection $tenantConnection

Pay attention to

I noticed, some PnP action are not working as expected

Conclusion

This solution work but has some limitation. I would prefer to use Azure App registration with enough permission to perform my task.

Comments

Popular posts from this blog

How to give app access on a specific SharePoint site using Azure AD API permission

Guest user can't access Client Side Assets resources in SharePoint App Catalog site

Ensure SharePoint User with Power Automate