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:
- Get all site collections - Get-SPSite
- For each site collection iterate each site group - $site.RootWeb.sitegroups
- For each site group iterate each user account - $group.users
- 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.
# 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.