Friday, October 30, 2015

Add SharePoint Security Group to All Lists or Libraries in a Site using PowerShell



This is sometimes very hectic for admins to add a new SharePoint Security group to a number of Lists and Libraries.

Using below code, it will be very easy to add a security group to all lists and libraries.

If you want to add security group to a specific type of library, you can add filter like the one below

if($spList.BaseTemplate -eq "10002")

For the information about base template follow the link


# Get Site
$spSite = Get-SPSite http://siteurl
# Get all web in current site
$spWebs = $spSite.AllWebs
# Set Permission level in variable
$PermissionLevel = "Read"
# Loop All Webs in site
foreach($web in $spWebs)
{
    # Get the Site Group from current Web which you want to add in Permissions for List/Library
       $spGroup = $web.SiteGroups["Visitors"]
    # Loop through all the lists/Libraries
       foreach($spList in $web.Lists)
       {
      
             
              # Break in Inheritance, this will allow you to add groups, otherwise it will not allow
              $spList.BreakRoleInheritance($true);
              # create Role Assignment  
              $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($spGroup)
              # Get the RoleDefinition for permission level
              $roleDefinition = $web.RoleDefinitions[$PermissionLevel];
              # Bind Role Definition
              $roleAssignment.RoleDefinitionBindings.Add($roleDefinition);
              # Add Role to List
              $spList.RoleAssignments.Add($roleAssignment)
              # Turn the Inheritance ON
              $spList.BreakRoleInheritance($false);
              # Update List
              $spList.Update();

             
       }
}

$spSite.Dispose()
$spWebs.Dispose()

No comments:

Post a Comment