Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / PowerShell

Cleaning up deleted AD accounts from SharePoint groups

0.00/5 (No votes)
30 Nov 2014CPOL 18.1K  
Script to remove deleted AD accounts from SharePoint groups

Introduction

I prefer using AD Security Groups in SharePoint Groups, but sometimes adding AD User accounts into SharePoint groups has its advantages. The problem with adding AD user accounts into SharePoint Groups is when the AD user account is deleted (e.g. user resigned). This leaves a 'ghost' of the account entry in your SharePoint groups.

These 'ghost' accounts do not pose any performance or security issue.

These 'ghost' accounts do however raises unnecessary questioning when audited and also present unpleasant aesthetics when viewing the group members, especially if the photos are synchronized with AD thumbnail photos.

Using the code

The flow the code is as follows:

  1. Get all site collections - Get-SPSite
  2. For each site collection iterate each site group - $site.RootWeb.sitegroups
  3. For each site group iterate each user account - $group.users
  4. Check each user account - varies depending on authentication method used
    Remove non-existing user accounts - $group.removeuer($user)

The following is the PowerShell code. Please replace "yourdomain" with your domain name.

C++
# File: SPRemoveDeletedADUsers
# Description: Remove Deleted AD users from SharePoint groups
Add-PsSnapin Microsoft.SharePoint.Powershell

$sites = Get-SPSite -Limit All

foreach ($site in $sites) {    
    $groups = $site.RootWeb.sitegroups
    foreach ($group in $groups) {
        foreach ($user in $group.users) {
            # Skip All Authenticated Users, General groups
            if ($user.userlogin -eq "c:0(.s|true" -or $user.userlogin -eq "c:0!.s|windows") {
                continue;
            }
            if ($user.IsDomainGroup) {
                # Skip Security Groups
            }
            else {
                # Get user login
                $splitline = $user.userlogin.split("\");
                $samid = $splitline[1];
                if ($user.userlogin.contains("yourdomain"))
                {
                    if (dsquery user -samid $samid) {
                        # Check if user exists in atrapa AD.
                    }
                    else {
                        $group.removeuser($user);
                    }
                }
            }
        }
    }
}

Download PowerShell script SPRemoveDeletedADUsers.ps1.txt

History

Dec 1, 2014 - First article baseline.

Dec 4, 2014 - Added PowerShell script as attachment.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)