In this blog post, we’ll explore a PowerShell script that automates the process of adding users to SharePoint Online (SPO) site collections. This script is particularly useful when you have a large number of users to add across multiple site collections.

Script Breakdown

Here’s the script we’ll be discussing:

$TenantUrl = "https://<site URL>-admin.sharepoint.us"
$CSVPath = "D:\Migratedsites.csv"

Connect-SPOService -Url $TenantUrl

$Useraccounts = @("AdeleV@mstechtalkdemodev.onmicrosoft.com","alexW@mstechtalkdemodev.onmicrosoft.com","Ben.Jones@mstechtalkdemodev.onmicrosoft.com")

$SiteCollections = Import-Csv -Path $CSVPath
 
ForEach ($Site in $SiteCollections)
{
    $siteUrl = $Site.URL
    Write-host "Creating Site Collection:" $siteUrl -f Yellow
    $group = Get-SPOSiteGroup -site $siteUrl | Select Title, Roles, Users  | Where-Object {$_.Roles -eq "Edit"}
    $group[0].Title
    
    ForEach($UserAccount in $Useraccounts)
    {
      Add-SPOUser -Site $siteUrl  -Group $group[0].Title -LoginName $UserAccount
    }

    Write-host $siteUrl "`t users added successfully!" -f Green
}

Let’s break it down:

  1. Tenant URL and CSV Path: The script starts by defining the URL of your SharePoint Online admin center ($TenantUrl) and the path to a CSV file ($CSVPath) that contains a list of site collections.
  2. Connecting to SPO Service: Connect-SPOService -Url $TenantUrl connects to the SharePoint Online Service with the provided tenant URL.
  3. User Accounts: An array of user accounts to be added to the site collections is defined.
  4. Importing Site Collections: The script imports the CSV file that contains the list of site collections.
  5. Iterating Over Site Collections: The script then iterates over each site collection in the CSV file.
  6. Retrieving Group and Adding Users: For each site collection, the script retrieves the group with “Edit” role and adds each user to this group.
  7. Success Message: Finally, a success message is printed after all users have been added to the current site collection.

Importance of the Script

This script is a powerful tool for SharePoint Online administrators. It automates a task that could be time-consuming and error-prone if done manually, especially when dealing with a large number of users and site collections. By using this script, administrators can ensure that all specified users are added to the appropriate SharePoint Online site collections with the correct permissions, saving time and reducing the risk of errors.

Adnan Amin is a Microsoft MVP for Microsoft 365 (since 2015) and a Senior Microsoft Consultant. He writes practical guides and PowerShell scripts for SharePoint, OneDrive, Teams and Copilot admins.

Leave a Reply

Your email address will not be published. Required fields are marked *