I will be executing a script to remove permissions from a SPitem
. However, a rollback plan is required and I am required to create a separate script which will add the permission of the user back to the SPitem
if required.
Below is my code snippet which removes a user from the SPitem
:
ForEach ($RDfolderId in $RDfolderSplit)
{
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewXml = "@<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>$RDfolderId</Value></Eq></Where></Query></View>"
$RDfolder = $RDlist.GetItems($query)
foreach($role in $RDfolder.RoleAssignments)
{
if ($role.Member.Name.Equals($userToAction))
{
#$RDitem.BreakRoleInheritance($true)
#$RDitem.RoleAssignments.RemoveById($roleAssignment.Member.ID)
#$RDitem.Update()
}
}
}
I have seen code samples online on adding roles
back to the SPitem
. However, there is an additional field RoleDefinitions
declared.
Is it compulsary to have the value declared when adding a user to a SPitem
?
Below is the code sample for adding:
$web = Get-SPWeb http://sp-2010
$account = $web.EnsureUser("SHAREPOINT\mray")
$role = $web.RoleDefinitions["Contribute"] #is this value compulsory?
$list = $web.Lists["Shared Documents"]
$list.BreakRoleInheritance($true)
$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
$assignment.RoleDefinitionBindings.Add($role)
$list.RoleAssignments.Add($assignment)
$list.Update()
$web.Dispose()
Short answer - Yes.
Let's break this sample up and explain each part:
$web
- SharePoint Web object aka. Site we are working on.$account
- User account we are working with.$role
- This is the Role Definition aka permissions like Contribute/Read/Approve. Yes. This is mandatory as it is the permissions you are going to add back.$list
- The List we are working with.BreakRoleInheritance
- This is if we need unique permissions on the List and to turn inheritance off. We don't have to do this every time, and likely in this example, you don't have to break inheritance.Now, we are onto the permissions pieces.
$assignment
- First, we need to get all the SharePoint roles currently assigned to our user.Add($role)
- Add the Role Definition i.e. "Contribute" to the user object. This does nothing to the list on SharePoint.Add($assignment)
- Add user with the new permissions to the List object. This does nothing to the list on SharePoint. We are manipulating the end state of the list that we want.Update
- Now do something on SharePoint. Actually apply the changes we have made to the List object to SharePoint.Dispose
- cleanup our objects.Now. Saying all of that. This is a good script for setting permissions. You also have a script for removing permissions. The point of a rollback script is that you need to record what those permissions originally were before you remove them. i.e. once you remove them, there isn't a magic undo button. ;-)