Thursday, September 25, 2014

Power Shell Script to grant a group permission recursively in a SharePoint Library


My task today was to write a script to recursively grant this particular group "full permission" in this document library.Obviously this is a tedious task especially when you have lots of items.
So Power shell to the rescue. I hope someone out there can use it.




##
#Make Sure snapin is loaded
##

$ver = $host | select version
if($Ver.version.major -gt 1) {$Host.Runspace.ThreadOptions = "ReuseThread"}
if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ea 0))
{
    Write-Progress -Activity "Loading Modules" -Status "Loading Microsoft.SharePoint.PowerShell"
    Add-PSSnapin Microsoft.SharePoint.PowerShell
}

#Here we want to give Full Control permission to SharePoint_SP_Team on all items this library recursively
$web = get-SPWeb("http://yourServerhere")
$list = $web.Lists
$PermissionLevel = "Full Control"
$GroupName = "SharePoint_SP_TEAM"
if ($list -ne $null)
{
    #Go through each Item and Change Permission
    foreach($RootItem in $list)
    {
        if($RootItem.Hidden -eq $False)
        { 
            if ($RootItem.HasUniqueRoleAssignments -eq $False)
            {
                $RootItem.BreakRoleInheritance($True)
            }

            if ($RootItem.HasUniqueRoleAssignments -eq $True)
            {
                ForEach ($SiteGroup in $web.SiteGroups)
                {                   

                    if ($SiteGroup.Name -match $GroupName)
                    {
                        write-host $SiteGroup.Name
                        $GroupName = $SiteGroup.Name
                        $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($SiteGroup)
                        $roleDefinition = $web.RoleDefinitions[$PermissionLevel];
                        $roleAssignment.RoleDefinitionBindings.Add($roleDefinition);
                        $RootItem.RoleAssignments.Add($roleAssignment)
                        $RootItem.Update();
                        write-host $RootItem.Title
                        Write-Host "Successfully added <$GroupName>" -foregroundcolor Green
                    }               
              
             }
            }
         }
    }
}


No comments:

Post a Comment