Search This Blog

Wednesday, August 31, 2016

Loop through user profiles using console app


Use the following code to loop through all user profiles using a c# console app:
var siteUrl = "http://yoursite";

SPSecurity.RunWithElevatedPrivileges(delegate()
{
  using (SPSite site = new SPSite(siteUrl))
  {
    try{
      SPServiceContext serviceContext = SPServiceContext.GetContext(site);
      UserProfileManager upMananger = new UserProfileManager(serviceContext);

      foreach (UserProfile profile in upMananger)
      {
        //Add your logic here..
        Console.WriteLine("Found: " + profile["AccountName"]);
      }
    }
    //Catch exceptions here, ex. NullReferenceException
    catch (System.Exception ex){
      //Handle exceptions
    }
  }
});

Some useful tips to avoid errors:
- Run the console application as Administrator
- Grant your account full control to User Profile Service Application (Fix NullReferenceException)




No comments:

Post a Comment