Wednesday, September 11, 2013

Set Permissions on Multiple Sites using PowerShell

These days I had a request to add an Active Directory group with Contributor rights on a SharePoint Site Collection. Since many sites had broken inheritance, using the UI was not an option so I created a small PowerShell Script that enumerates all Webs and if the Inheritance is broken, it adds the group with the specified Role.

Notes:


  • The If command uses the $web.Url.Contains directive in order to modify the rights only on a subset of sites. If all Webs have to be crawled, use if ($web.HasUniquePerm -and $web.RequestAccessEnabled) instead.
  • This script modifies permissions only on webs. Lists and Items with unique permission will not be touched.

if ((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
 Add-PSSnapin Microsoft.SharePoint.PowerShell
}


$site = Get-SPSite -Identity "http://spdev/sites/SiteCollection"


foreach($web in $site.AllWebs)
    {

    if ($web.HasUniquePerm -and $web.RequestAccessEnabled -and ($web.Url.Contains("/SiteCollection/BU1") -or $web.Url.Contains("/SiteCollection/BU2")))
        {
            $account = $web.EnsureUser("Domain\QATeam")
            $role = $web.RoleDefinitions["Contribute"]

            $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
            $assignment.RoleDefinitionBindings.Add($role)

            $web.RoleAssignments.Add($assignment)
        }
    $web.Dispose()
    }
$site.Dispose()


References

2 comments: