SharePoint Add Users In SCA Using PnP PowerShell

This PowerShell used to add any other user in SCA (Site Collection Administrator). You have to add all sites in .csv file (mention full path of .csv in $csvPath). PowerShell code will read the .csv file and it will one by one connect sites using PnP. You have to add all users in $allEmailIDs array. $allErrorSites will print all error sites.
 
The error will be,
  • If you do not have access to that site.
  • If the email id is not valid.
Use below code in PowerShell,
  1. $csvPath = ".CSV FILE PATH"  
  2. $allSitesUrls = Get - Content $csvPath  
  3. $allEmailIDs = @("EMAIL ID - 1""EMAIL ID - 2")  
  4. $allErrorSites = @()  
  5. try {  
  6.     ForEach($singleSiteUrl in $allSitesUrls) {  
  7.         : InnerLoop ForEach($emailID in $allEmailIDs) {  
  8.             try {  
  9.                 Write - Host "Start Process for : $($singleSiteUrl)";  
  10.                 Connect - PnPOnline $singleSiteUrl - UseWebLogin  
  11.                 $clientContext = Get - PnPContext  
  12.                 $web = $clientContext.Web;  
  13.                 $clientContext.Load($web);  
  14.                 $clientContext.ExecuteQuery();  
  15.                 $spUser = $clientContext.Web.EnsureUser($emailID);  
  16.                 $spUser.IsSiteAdmin = $true;  
  17.                 $spUser.Update();  
  18.                 $clientContext.Load($spUser)  
  19.                 $clientContext.ExecuteQuery()  
  20.                 Write - Host "SCA access provided to: $($spUser.Email) to site $($web.Title) ($($web.Url)";  
  21.             } catch {  
  22.                 #Add the object with property to an Array  
  23.                 $allErrorSites += $singleSiteUrl;  
  24.                 [string] $FuncName = $MyInvocation.MyCommand.Name;  
  25.                 Write - Host - Message $_ - FunctionName $FuncName;  
  26.             }  
  27.         }  
  28.     }  
  29.     #It will print all sites which got error  
  30.     Write - host - f Red $allErrorSites;  
  31. catch {  
  32.     [string] $FuncName = $MyInvocation.MyCommand.Name;  
  33.     Write - Host - Message $_ - FunctionName $FuncName;  
  34. }