How to programmatically change Active Directory password

Jeff picture Jeff · Jun 30, 2009 · Viewed 88.2k times · Source

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.

Answer

tvanfosson picture tvanfosson · Jun 30, 2009

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();
  }
}