kwizcom banner advertisement

Remove All Users from SharePoint Site or List with PowerShell

Requirement: There is a SharePoint 2013 list lot of user permissions. Wanted to remove all user permissions from that SharePoint list. So tried removing all users, but SharePoint gave "You have chosen to delete too many groups at once. Select fewer groups and try again." when choosing All users check box and Remove them from SharePoint site or group.
You have chosen to delete too many groups at once. Select fewer groups and try again.

So the problem here is: We can't delete users in bulk when it exceeds the maximum count by SharePoint. Here is my nifty PowerShell scripts to remove all users from SharePoint site or List.

PowerShell script to remove all user permission from SharePoint list:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables
$SiteUrl="http://your-sharepoint-site.com" 
$ListName="Your-List-Name" 

#get the Web
$web = Get-SPWeb $SiteUrl
#Get the List
$list = $web.Lists[$ListName]

#If the List is not using Unique permissions, Break inheritance
if(!$list.HasUniqueRoleAssignments)
{
    #Break list inheritance - without copying users
    $list.BreakRoleInheritance($false)
}

#Remove all users from the list
 for ($i = $list.RoleAssignments.Count - 1; $i -ge 0; $i--)
    {
      $RoleAssignment = $list.RoleAssignments[$i]
      $list.RoleAssignments.RemoveByID($RoleAssignment.Member.ID)
      write-host "Removed User/Group :" $RoleAssignment.Member.name
    } 

Remove all users from SharePoint site
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Site collection URL 
$SiteUrl="http://demo.sp.cloudservicesme.com" 

#get the Root Web
$web = Get-SPWeb $SiteUrl

#Get All Users of the site collection
$UserAccounts = @()
foreach ($user in $web.SiteUsers)
{
   $UserAccounts = $UserAccounts + $user.loginname
}

#Remove all users one by one.
foreach ($user in $UserAccounts)
{
    try
    {
        #Set the Error Action
        $ErrorActionPreference = "Stop"

        #Remove User if not site admin
        if(!$web.SiteUsers[$User].isSiteAdmin)
        {
            $web.SiteUsers.Remove($user)
            Write-host "User Removed :" $user -ForegroundColor Green
        }
    }
    catch    
    {
        Write-host "Failed to remove the user:" + $user -ForegroundColor Red   
    }
    Finally
    {
        #Reset the Error Action to Default
        $ErrorActionPreference = "Continue"
    } 
}
Remove All Users from SharePoint Site or List with PowerShell Remove All Users from SharePoint Site or List with PowerShell Reviewed by Salaudeen Rajack on 12:07 PM Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.