Saturday, October 3, 2015

Bulk User Profile Deletion in SharePoint 2010 / 2013

Sometimes we are not sure about which AD objects to be imported from Active Directory to SharePoint and later when we come to know AD objects we need to delete existing imported profiles and re run the full synchronization.
In order to delete existing profiles below Power shell script will help us to delete all profiles except Farm Account from SharePoint User Profile.

PowerShell Script - Delete All User Profiles - SharePoint 2010 / SharePoint 2013
#The scripts is distributet "as-is." Use it on your own risk. The author give no warranties, guarantees or conditions.
#Add SharePoint PowerShell SnapIn if not already added

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

#Set my site host location. In this example I use host location on the same web application as the portal itself.
#MS recommends to use different web application for hosting your personal sites
#In this example My Site Host is on location http://sp2010/my/mysite/

$site = new-object Microsoft.SharePoint.SPSite("sp2010/my/mysite/");
$ServiceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($site);

#Get UserProfileManager from the My Site Host Site context

$ProfileManager=new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)
$AllProfiles = $ProfileManager.GetEnumerator()
foreach($profile in $AllProfiles)
{
$DisplayName = $profile.DisplayName
$AccountName=   $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName].Value

#Do not delete setup (admin) account from user profiles. In this case account is Domain\XYZ

 if($AccountName -ne " Domain\XYZ ")
{
$ProfileManager.RemoveUserProfile($AccountName);
write-host "Profile for account ", $AccountName, " has been removed"
}
}
write-host "Finished."

$site.Dispose()

No comments:

Post a Comment