Powershell – To add site collection admins in bulk

Hello friends, in this article, we will see how we can assign site collection admin role to multiple user on multiple sites using powershell.

For this you need to summarize the site links and user email address in a csv format as shown below:

Powershell

<###############################################################
.SYNOPSIS
Script to set site collection administrator in SP Online
.DESCRIPTION
Sets site collection administrators for site collections in SP Online
.NOTE
SharePoint Online Management Shell needs to be installed in local
machine in order to execute the script
###############################################################>

Function Check-SiteExists($SiteUrl)
{
    $errpref = $ErrorActionPreference #save actual error preference
    $ErrorActionPreference = "silentlycontinue"

    return (Get-SPOSite -Identity $SiteUrl) -ne $null

    #return (Get-SPOSite -Identity $SiteUrl) -ne $null
    $ErrorActionPreference = $errpref #restore previous error preference    
}

Set-ExecutionPolicy Unrestricted -Force

$inputFilePath = "D:\Mayuresh\Sites1.csv"

$credential = Get-Credential

#Adding SharePoint Online Powershell module to the current session.
Import-Module MSOnline

#Connect-MsolService -Credential $credential

#Get-MsolUser

#Adding SharePoint Online Powershell module to the current session.
Import-Module Microsoft.Online.SharePoint.PowerShell

#Connects a SharePoint Online global administrator to a SharePoint Online connection
Connect-SPOService -url https://myclassbook-admin.sharepoint.com -Credential $credential

#import csv file containing site collection details
$sites = Import-Csv $inputFilePath
ForEach ($site in $sites)
{
    $SiteCollURL = $($site.Url)
    $SiteCollectionAdmin = $($site."Site Collection Admin")
   
    try
    {
        #Add Site collection Admin
        Set-SPOUser -site $SiteCollURL -LoginName $SiteCollectionAdmin -IsSiteCollectionAdmin $False
    }
    catch
    {
        Write-Host -ForegroundColor Red "Please check if the user "$SiteCollectionAdmin" is valid"
    }
}

#Disconnects the SharePoint Online service.
Disconnect-SPOService

Download: Assign site owner for multiple site

Leave a Reply