Delete inactive users in user profiles

For more detail there is a very good article about how mysite clean up job is working.

Well , if you have a scenario that you can not run somehow my site clean up job, or intentionally stopped for a reason and if you need to clean inactive user profiles following powershell script will help you to remove inactive (non-imported) profiles in User Profile Service in SharePoint.

#PowerShell Script – Delete Inactive User Profiles – SharePoint 2010/2013

#The scripts is distributet “as-is.” Use it on your own risk. The author give no warranties, guarantees or conditions.

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

$site = Get-SPSite “<site url>
$ctx = Get-SPServiceContext $site
$pm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($ctx)

$ProfileDB = Get-SPDatabase | ? { $_.Type -eq “Microsoft.Office.Server.Administration.ProfileDatabase”}

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $ProfileDB.DatabaseConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = “select NTName,RecordId from UserProfile_Full where bDeleted=1″
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet

Write-host “Total Count: ” $DataSet.Tables[0].Rows.Count
Write-Host “Following Inactive Accounts will be deleted !”

foreach($user in $DataSet.Tables[0].Rows)
   write-host “Planning to delete :” $user[“NTName”] -ForegroundColor Green
   $profile = $pm.GetProfile($user[“RecordId“])
    #To enable delete operation remove comment out for below line
    #write-host $user[“NTName”] is deleted!!! -ForegroundColor Red
write-host “Operation Completed !”



About bpostaci
Escalation Engineer in Microsoft.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: