Deleting User Profiles Using PowerShell
There are many reasons why we would want to use a PowerShell shell script to delete user profiles.
- We don't want to use or trust the My Site Cleanup job.
- We have a batch of stub user profiles that need to be deleted.
- We just want to delete some user profiles for testing purposes.
- We don't want to wait 30 days before the User Profile is deleted by the My Site Cleanup timer job(applies only to SharePoint 2016)
NOTE: Deleting user profiles with this script will delete just the user profile. This will not delete their My Site or send out that notification like the My Site cleanup job. WARNING: This script will delete user profiles specified in the file. The only other means to recover the user profile is to restore the Profile DB from backup.
The List
There are a few ways that we can gather a list of user profiles. We can query the profile database, run GetNonImportedObjects, or we already have a list that we want to delete.
Profile DB query - Select NtName from UserProfile_Full with(nolock) where bdeleted=1
PowerShell
$upa = Get-spserviceapplication | ?{$_.typename -match "profile"}
Set-SPProfileServiceApplication $upa -GetNonImportedObjects $true | out-file c:\temp\NonImportedProfiles.txt
We just want the list to be a text file with the a NTName on each line.
Parameters
We will just need to modify the top 3 lines to adjust it for our farm. The first is $siteurl. This should be URL that is consuming from the User Profile Service Application. The $file is the location and name of the input file we created above. The $log is for the location of the log file(Yes, there is logging with my PowerShell scripts). Just make sure the directory is created.
One gotcha is to make sure the account running this script has permissions to the User Profile service application. This can be accomplished in Central Admin with adding the account into Permissions with Full Control.
Link to the Script
Comments
- Anonymous
February 21, 2018
Its a nice Article but I think Heading should change to "Delete user profile from SharePoint service application using PowerShell "