How to remove the user profile from SharePoint 2010 using C# and Powershell


In this article we will be seeing how to remove the user profile based on the specified Account Name from the user profile database in SharePoint 2010.

UserProfileManager.RemoveUserProfile(string strAccountName) => Used to remove the user profile from the user profile database based on the specified Account Name in SharePoint 2010.

Using C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using System.Web;

namespace UP
{
    class Program
    {
        static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://serverName:12345/"))
            {
             //get the server context
                ServerContext context = ServerContext.GetContext(site);
                UserProfileManager upm = new UserProfileManager(context);
                string StrAccountName = "sptestuser";
                upm.RemoveUserProfile(StrAccountName);
            }
        }
    }
}


Using PowerShell:

$site=Get-SPSite "http://serverName:12345/"
$context=[Microsoft.SharePoint.SPServiceContext]::GetContext($site)
$strAccountName = "sptestuser";
$userProfileManager = [Microsoft.Office.Server.UserProfiles.UserProfileManager, Microsoft.Office.Server.UserProfiles, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c]
$upm=New-Object $userProfileManager($context)
$upm.RemoveUserProfile("$strAccountName")