December 27, 2012

Powershell - Remove User account permissions from all sites

Use Cases:
When you create a site with unique permissions and break role inheritance at list or list item level, sharepoint will automatically add SHAREPOINT\System or site collection admin directly to Site Permissions. Here is the script that you can use to remove those users.
How​
 function RemoveAccountFromAllSites ($siteURL, $accountName, [switch]$skipRootSite)
 {
    #Get Site Collection
    $site = Get-SPSite $siteURL
 
    #Check if the accountName variable contains a slash - if so, it is an AD account
    #If not, it is a SharePoint Group
    $rootWeb = $site.RootWeb
    if ($accountName.Contains("\")) { $account = $rootWeb.EnsureUser($accountName) }
    else { $account = $rootWeb.SiteGroups[$accountName] }
 
    $rootWeb.Dispose()
    
    #Step through each site in the site collection
    $site | Get-SPWeb -limit all | ForEach-Object {
        
        #Check if the user has chosen to skip the root site - if so, do not change permissions on it
 
        if (($skipRootSite) -and ($site.Url -eq $_.Url)) { write-host "
Root site" $_.Url "will be bypassed" }
        else {
            #Check if the current site is inheriting permissions from its parent
            #If not, remove permissions on current site
            if ($_.HasUniqueRoleAssignments) {
                #write-host "
Removing account" $accountName "from site" $_.Url
                $_.RoleAssignments.Remove($account)
            }
            else {
                write-host "
Site" $_.Url "will not be modified as it inherits permissions from a parent site."
            }
        }
    }
    #Display completion message and dispose of site object
    #write-host "
Operation Complete."
    $site.Dispose()
}
Conclusion:
Script will check if site has unique permissions or not. Skips and don't do anything if site is not having unique permissions. Does what is expected if site is having unique permissions.
If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment