SharePoint Online: Bulk Import Users to Groups from a CSV File using PowerShell

Requirement: Bulk add users from a CSV file to SharePoint Online Groups

Here is the CSV file with users and groups data:
sharepoint online bulk add users to group

SharePoint Online: Bulk Add Users to Group using PowerShell 
SharePoint Online groups helps to manage security effectively by combining users accounts and security groups. Typically, Active Directory user and security groups will be added to SharePoint groups, and then SharePoint groups are used to assign permissions within sites. Here is my PowerShell script to import users from a CSV file to SharePoint Online groups.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Function Import-SPOUserFromCSV($CSVFile)
{  
    #Get data from CSV
    $UserData = Import-CSV $CSVFile

    #Get Credentials to connect
    $Cred = Get-Credential

    ForEach($Row in $UserData)
    {
        #Get Data from CSV
        $SiteURL = $Row.SiteURL
        $GroupName= $Row.GroupName
        $UserAccount = $Row.UserAccount
  
        Try {
            #Setup the context
            $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
            $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
     
            #Get the Web and Group
            $Web = $Ctx.Web
            $Group= $Web.SiteGroups.GetByName($GroupName)
 
            #Resolve the User
            $User=$web.EnsureUser($UserAccount)
 
            #Add user to the group
            $Result = $Group.Users.AddUser($User)
            $Ctx.Load($Result)
            $Ctx.ExecuteQuery()
 
            write-host  -f Green "User '$UserAccount' has been added to '$GroupName' in Site '$SiteURL'"
        }
        Catch {
            write-host -f Red "Error Adding user to Group!" $_.Exception.Message
        }
    }
}

#Call the function
Import-SPOUserFromCSV "C:\Temp\UserData.csv"

Here is my another post for SharePoint On-Premises to version: Import users from CSV File to SharePoint using PowerShell
SharePoint Online: Bulk Import Users to Groups from a CSV File using PowerShell SharePoint Online: Bulk Import Users to Groups from a CSV File using PowerShell Reviewed by Salaudeen Rajack on June 11, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.