SharePoint Online: Add Bulk Users and Groups using PowerShell

Requirement: Add multiple users and Groups to SharePoint Online sites in bulk

How to Create Multiple Groups and Users in SharePoint Online?

I had to create several SharePoint User Groups and add users to those groups on different sites. In this blog post, let’s take a look at how to add multiple users and groups to SharePoint Online sites using PowerShell. This can come in handy if you want to automate the process of adding users and groups to sites. Here is my CSV file with the users and groups data:

add multiple users to sharepoint online group powershell

PowerShell to Add Users and Groups to SharePoint Sites

This PowerShell script comes in handy when you want to quickly add a large number of users and groups to multiple SharePoint Online sites. It checks if a group already exists on the site. If not, it creates a new SharePoint Group and then assigns permissions to the group. Finally, it adds given users to the respective group.

#Config Variables
$CSVPath = "C:\Temp\UsersAndGroups.csv"

#Get Data from CSV
$CSVData =  Import-CSV -Path $CSVPath

Try {
    ForEach($Row in $CSVData)
    {
        #Connect to the Site with PnP PowerShell
        Connect-PnPOnline -Url $Row.SiteURL -Interactive
     
        #Check if the group exists already
        If((Get-PnPGroup | Where { $_.Title -eq $Row.GroupName}) -eq $Null)
        {
            #Create SharePoint Online Group
            $Group = New-PnPGroup -Title $Row.GroupName -ErrorAction Stop
            Write-Host -f Green "Group '$($Row.GroupName)' Created Successfully!"
        }
        Else
        {
            #Get the Group
            $Group = Get-PnPGroup -Identity $Row.GroupName
        }
        #Set Group Permissions
        Set-PnPGroupPermissions -Identity $Group -AddRole $Row.Permission

        #Add Users to the Group
        $Users =  $Row.Users -split ";"
        ForEach($User in $Users)
        {
            $NewUser = Add-PnPGroupMember -LoginName $User.Trim() -Identity $Group
            Write-host -f Green "`tAdded $User to $($Group.Title)"
        }
    }
}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

My related posts on adding multiple SharePoint groups and users to SharePoint Online sites with PowerShell:

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

One thought on “SharePoint Online: Add Bulk Users and Groups using PowerShell

  • Hi,

    Thank you for the script, it’s much appreciated.

    When I try running it however, I get the following error:

    “Error: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))”

    Do you have any idea of what could be causing it?

    Thank you

    Reply

Leave a Reply