add multiple AD security groups to multipe site collections using powershell from csv file

DK 46 Reputation points
2022-04-13T18:28:48.087+00:00

How can i add multiple AD security groups to multiple site collections using powershell? i have csv file which contains data as shown below,
192812-image.png

Microsoft 365 and Office | SharePoint Server | For business
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. CaseyYang-MSFT 10,466 Reputation points
    2022-04-14T07:26:29.977+00:00

    Hi @DK ,

    Here is a article about SharePoint Online: Add Bulk Users and Groups using PowerShell. You could add users and groups to different sites using below PowerShell commands.

    1.Download the CSV Template:

    193000-1.jpg

    2.PowerShell commands:

    #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  
    }  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.