Monday, October 7, 2019

Remove all users from particular Sharepoint Group

#Load SharePoint Online 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 to remove all users from a group
Function Remove-AllUserFromGroup()
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $GroupName
    )
   Try {
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials
       
        #Get the Group
        $Group=$Ctx.web.SiteGroups.GetByName($GroupName)
        $Ctx.Load($Group)
        $Ctx.ExecuteQuery()

        #Get users of the group
        $GroupUsers = $Group.Users
        $Ctx.Load($GroupUsers)
        $Ctx.ExecuteQuery()

        #Remove all users from the group
        ForEach($User in $GroupUsers)
        {
            $Group.Users.RemoveByLoginName($User.LoginName)
        }
        $Ctx.ExecuteQuery()
        Write-host "All Users are Removed from the Group!" -ForegroundColor Green     
    }
    Catch {
        write-host -f Red "Error Removing All Users from Group!" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL = "Site Collection URL"
$GroupName="Group Name from which you want to delete"

#Call the function to remove all users from group
Remove-AllUserFromGroup -SiteURL $SiteURL -GroupName $GroupName

No comments:

Post a Comment