SharePoint Online: Clone User Group Memberships using PowerShell

Requirement: Clone a user's group permissions to another user in a SharePoint Online Site.

PowerShell to Clone User's Group Memberships in SharePoint Online:
It's a common real world scenario that when someone leaves the organization and somebody else takes that role they want the same permissions! While the requirement sounds simple, its really cumbersome to achieve it through web user interface. Basically, you have to go to each group where the source user is member of, and add target user to it. Here is how we can automate this task by using PowerShell:
#Function to copy group memberships from one user to another
Function Clone-SPOUserGroupPermission($SiteURL, $SourceUserID, $TargetUserID)
{
    Try {
        #Get the Site collection
        $Site = Get-SPOSite $SiteURL 
    
        #Get the Source user
        $SourceUser = Get-SPOUser -Site $Site -LoginName $SourceUserID

        #Get All groups of the source User
        $UserGroups = $SourceUser.Groups
    
        If($UserGroups.Count -gt 0)
        {
            Write-host -f Yellow "Found the User Member of $($UserGroups.Count) Group(s)..."

            #Loop through each group of the source user and add target user to that group
            ForEach ($Group in $UserGroups)
            {
                #Add Target User to the Group
                Add-SPOUser -Site $Site -LoginName $TargetUserID -Group $Group | out-null    
                Write-Host -f Green "Added $TargetUserID to Group '$Group'"
            }
        }
    }
    Catch {
        Write-host $_.Exception.Message -f Red
     }
}

#SharePoint Online Admin Center URL
$AdminCenterURL = "https://crescenttech-admin.sharepoint.com"
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$SourceUserID ="John@TheCrescentTech.com"
$TargetUserID ="Peter@TheCrescentTech.com"

#Connect to SharePoint Online Admin Center
Connect-SPOService -Url $AdminCenterURL -Credential (Get-Credential)

#Call the Function
Clone-SPOUserGroupPermission -SiteURL $SiteURL -SourceUserID $SourceUserID -TargetUserID $TargetUserID 
You can also use "Get-SPOSite" cmdlet to get all site collections and call the function to copy user's group memberships to another user.
SharePoint Online: Clone User Group Memberships using PowerShell SharePoint Online: Clone User Group Memberships using PowerShell Reviewed by Salaudeen Rajack on April 19, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.