Freigeben über


Removing a user's site collection administrator privileges and security group memberships

A peer of mine, Jonathan Dimino, recently wrote a post on his TechNet blog to provide a PowerShell script for changing the Primary and Secondary site collection administrators assigned to a site collection.  Along with replacing the Primary/Secondary site collection administrators, it is sometimes necessary to remove a user from all site collection administrator privileges and all security groups within SharePoint.  Unless your farm is extremely small and restricts the use of unique permissions, this can be a daunting task to perform manually.  The following script can be used to remove a user's site collection administrator privileges and all security group memberships.  The script is provided AS IS and should be tested thoroughly before execution in a production environment.

NOTE: This script should be run after the script referenced above is used to replace the user from all Primary/Secondary site collection administrator assignments. The following script will error is you attempt to remove a user's privileges while the user is still assigned as a Primary/Secondary site collection administrator.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

# *********************** !!!!!!IMPORTANT!!!!!!! ********************************
# THIS SCRIPT WILL REMOVE ALL PERMISSIONS FROM ALL SITES/GROUPS FOR THE USERS
# IDENTIFIED IN THE "oldAdmins" PARAMETER.
# *******************************************************************************

$sites = Get-SPSite -Limit ALL

$auditMode = $false

# Enumeration of accounts to be removed (add one line for each ID)
$oldAdmins = @()
$oldAdmins += "<domain\user id1>"
$oldAdmins += "<domain\user id2>"

foreach ($site in $sites)
{
    $admins = $site.RootWeb.SiteAdministrators
   
    $foundOldAdmins = $admins.GetCollection($oldAdmins)
   
    if ($foundOldAdmins.Count -gt 0)
    {
        if ($foundOldAdmins.Count -eq 1)
        {
            if ($auditMode)
            {
                Write-Output ("Would have removed " + $foundOldAdmins[0] + " in " + $site.RootWeb.Url)
            }
            else
            {
                Write-Output ("Removed " + $foundOldAdmins[0] + " in " + $site.RootWeb.Url)
                $admins.Remove($foundOldAdmins[0])
            }
        }
        else
        {
            if ($auditMode)
            {
                Write-Output ("Would have removed " + $foundOldAdmins + " in " + $site.RootWeb.Url)
            }
            else
            {
                Write-Output ("Removed " + $foundOldAdmins + " in " + $site.RootWeb.Url)
                $admins.RemoveCollection($OldAdmins)
            }
        }
       
    }

    # Clear the variable, just to be safe
    $foundOldAdmins = $null
   
    $site.Dispose()
}