Wednesday 11 May 2016

Clean up SharePoint User Profile Store using PowerShell

There is a solution using PowerShell without compiled code. Using PowerShell everything what is available in the server object model is available. First of all two assemblies must be referenced.
These assemblies are:
Those assemblies could be referenced using System.Reflection and the rest of the script is quite simple SharePoint Development. So get a context object, open profile service application get all use and delete them.

# Load required Assemblies for SharePoint Server and User Profile
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles")

# Central Adminstration URL or any Web Application
$url = "http://mainframe:48248"
# Create a new Context Object
$contextWeb = New-Object Microsoft.SharePoint.SPSite("http://mainframe");

# Get the right Service Context
$ServerContext = [Microsoft.Office.Server.ServerContext]::GetContext($contextWeb);

# create a new connection to the UserProfileManager
$UserProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServerContext);

# Ger all User Profiles
$Profiles = $UserProfileManager.GetEnumerator();

# Loop through user profile
foreach ($oUser in $Profiles ) {
# Remove Profile
$UserProfileManager.RemoveUserProfile($oUser.item("AccountName"));
}


This script can be extended to delete only specific users from user profile information. At the end I was able to solve my problem. My User Profile was deleted and recreated on first access and due profile import. Everything worked fine.
In the old days you had to write some custom command line tool to address those batch update and deletion task. With the introduction of PowerShell to SharePoint any possible administrative task could be accomplished by just use scripting.

No comments:

Post a Comment