Search code examples
c#active-directorydirectoryservices

How to programmatically change Active Directory password


I have a set of test accounts that are going to be created but the accounts will be setup to require password change on the first login. I want to write a program in C# to go through the test accounts and change the passwords.


Solution

  • You can use the UserPrincipal class' SetPassword method, provided you have enough privileges, once you've found the correct UserPrincipal object. Use FindByIdentity to look up the principal object in question.

    using (var context = new PrincipalContext( ContextType.Domain ))
    {
      using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName ))
      {
          user.SetPassword( "newpassword" );
          // or
          user.ChangePassword( "oldPassword", "newpassword" );
    
          user.Save();
      }
    }