Saturday, June 14, 2014

Remove All Users from SharePoint Site, 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.


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



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...