Sunday, March 10, 2013

Break Inheritance and Add-Remove Item Level Permission with PowerShell

Requirement: 
Break the permission inheritance of a SharePoint list item and grant permission only to a specific user and group.

sharepoint Break Inheritance Add Remove Item Level Permission PowerShell

PowerShell Script to Add Item Level Permissions in SharePoint:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration parameters
$SiteURL = "https://portal.crescent.com/"
$ListName="Profiles"
$ItemID="12"

#Get the web and Item
$Web = Get-SPWeb $SiteURL
$List = $web.Lists[$ListName]
$Item = $List.GetItemById($ItemID)

#Break Inheritance - Remove all permissions
$Item.BreakRoleInheritance($False)

#Grant Contribute Permission to User
$user = $web.EnsureUser("Crescent\Antony")
$PermissionLevel="Contribute"
$RoleDefinition = $web.RoleDefinitions[$PermissionLevel]
$roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
$roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
$item.RoleAssignments.Add($roleAssignment)
$item.SystemUpdate();  

#Grant Read access to the Visitor Group
$GroupName="Crescent Portal Visitors"
$PermissionLevel="Read"
$Group = $web.SiteGroups[$GroupName]  
$roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)  
$roleDefinition = $web.RoleDefinitions[$PermissionLevel]
$roleAssignment.RoleDefinitionBindings.Add($roleDefinition);  
$item.RoleAssignments.Add($roleAssignment)  
$item.SystemUpdate(); 

How to Remove User Permissions from a List Item using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Configuration parameters
$SiteURL = "http://intranet.crescent.com"
$ListName="Project Tasks"
$ItemID="10"

#Get the web, Item and User Objects
$Web = Get-SPWeb $SiteURL
$List = $web.Lists[$ListName]
$Item = $List.GetItemById($ItemID)
$User = $web.EnsureUser("crescent\Tony")
$Group = $web.SiteGroups["Approvers"]  

#Break Inheritance - Without Copying current permissions
$Item.BreakRoleInheritance($True) #Breaks permission inheritance, if its not already!
$Item.RoleAssignments.Remove($User)
#$Item.RoleAssignments.Remove($Group)

$Item.SystemUpdate()

In an another requirement, we had to Set Item Level permission to a SharePoint Group to all documents in a specific document library with 100+ documents. Earlier, I wrote C# code to set Item level permission on Event Receiver to Set Item Level Permissions . This time let me do it with PowerShell for SharePoint 2007.

Set Item Level Permission to All Items in a List using PowerShell
# For MOSS 2007 compatibility
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Region MOSS2007-CmdLets
Function global:Get-SPSite()
{
  Param( [Parameter(Mandatory=$true)] [string]$SiteCollURL )

   if($SiteCollURL -ne '')
    {
    return new-Object Microsoft.SharePoint.SPSite($SiteCollURL)
   }
}
 
Function global:Get-SPWeb()
{
 Param( [Parameter(Mandatory=$true)] [string]$SiteURL )
  $site = Get-SPSite($SiteURL)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
            }
    return $web
}
#EndRegion

 Function AddItemLevelPermissionToGroup()
 {  
    #Define Parameters
    Param( [Parameter(Mandatory=$true)] [string]$SiteURL, 
           [Parameter(Mandatory=$true)] [string]$ListName, 
           [Parameter(Mandatory=$true)] [string]$GroupName,
           [Parameter(Mandatory=$true)] [string]$PermissionLevel )
 
 #Get the Web Application
    $Web=Get-SPWeb($SiteURL)
    
    #Get the List
    $list = $web.Lists[$ListName]
    if ($list -ne $null)  
    {  

    #Loop through each Item in the List
     foreach($item in $list.items)
   {
            #Check if Item has Unique Permissions. If not Break inheritence
            if($item.HasUniqueRoleAssignments -eq $False)  
              {  
               $item.BreakRoleInheritance($false)
               #False: Does removes all users & groups from Item's Permissions  
              } 
              
           if ($web.SiteGroups[$GroupName] -ne $null)  
               {
                #Get the Group from GroupName Parameter  
                $group = $web.SiteGroups[$GroupName]  
                $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)  
                #Get Permission Level, such as "Read", "Contribute", etc
                $roleDefinition = $web.RoleDefinitions[$PermissionLevel]
                $roleAssignment.RoleDefinitionBindings.Add($roleDefinition);  
                #Grant Access to specified Group
                $item.RoleAssignments.Add($roleAssignment)  
                #To Remove Access: Call  $item.RoleAssignments.Remove($group) . No Need for objects: roleAssignment, roleDefinition
                $item.SystemUpdate();  
                Write-Host "Successfully added $($PermissionLevel) to $GroupName group in $($Item.Name)" -foregroundcolor Green  
               } 
         }
  $Web.Dispose()          

    }
 }

#Call the Function to Grant Item Level Permission
#Parameters: $SiteURL, $ListName, $GroupName, $PermissionLevel
AddItemLevelPermissionToGroup "http://sharepoint.crescent.com/sites/sales" "Documents" "Approvers" "Read"

How to Break List Permissions and grant access to a user using PowerShell: 
Similarly, We can add users at List permissions.
#Get the User
$user = $web.EnsureUser('global\salaudeen')

$roleDefinition = $web.RoleDefinitions[$PermissionLevel]

$roleAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($user)
$roleAssignment.RoleDefinitionBindings.Add($roleDefinition)

$List.RoleAssignments.Add($roleAssignment)
$List.SystemUpdate();  
Write-Host "Successfully added $($user) to $($List.Name)" -foregroundcolor Green  



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:

2 comments :

  1. The Script is famous and helps great.But i have a strange Problem i dont know why. I want to filter the list items in the eachfor as follows:
    foreach($item in $list.items | Where $Item["aktiv"] -eq "Ja") .... Field AKtiv= Checkbox Ja/Nein. BUT: the filter doesnt work. why?
    Does anybody why? what is wrong in my filter Action?

    ReplyDelete
    Replies
    1. Use something like: $list.Items | Where-Object { $_["Status"] -eq "In Progress"} | foreach { }

      Delete

Please Login and comment to get your questions answered!


You might also like:

Related Posts Plugin for WordPress, Blogger...