0

I'm trying to remove all permissions from a list item (SharePoint 2013).

I worked out the following script that should do that:

$url = "https://Site"
$listName = "Tasks";

$SPWeb = Get-SPWeb $url;
$SPList = $SPWeb.Lists[$listName];
$SPItem = $SPList.GetItemById(1);

#break inheritance
 if ($SPItem.HasUniqueRoleAssignments -eq $False)
 {
 $SPItem.BreakRoleInheritance($true)
  }

#Remove all Permissions  
for ($i = 0; $i -lt $SPItem.RoleAssignments.Count; $i++)
{
  try
  {
  $SPItem.RoleAssignments.Remove($i)
  }
  catch
  {
  }
}
$SPItem.Update()

The problem is, that this script removes only the first half of the existing permissions on a list item. I have to run it four times to remove all permissions.

Does anybody have an idea?

1

The issue you have is, you are looping till index i reaches RoleAssignment count and within the loop you are removing the RoleAssignment one by one. This means, the loop count decreases by one. So, on every run, it will only loop half the total no of permissions. So, you have to run multiple times to delete all permissions. What you can do is create an infinite loop and keep deleting the permissions until count reaches 0.

I have another suggestion,

You are first breaking the permission inheritance and then removing individual permissions from the list. So, What I would do is, use false for the BreakRoleInheritance function argument value. This will not copy permissions from the parent site and it will keep only the current user permissions. Now, you only have to delete one permission.

So, replace $SPItem.BreakRoleInheritance($true) with $SPItem.BreakRoleInheritance($false)

1

Add a reversed loop based on RoleAssignments.Count and loop through this counter backward instead

$cpt = $list.RoleAssignments.Count - 1;
for ($i = $cpt; $i -ge 0; $i--)
{
    $list.RoleAssignments.Remove($i);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.