Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 211
Jeff Avatar asked Jun 30 '09 21:06

Jeff


People also ask

How do I change a password in PowerShell using Active Directory?

There are two ways to reset a user account password in PowerShell: The Set-ADAccountPassword cmdlet, included in the RSAT PowerShell module. The Active Directory Service Interface (ADSI) method.

What is the command to reset password in Active Directory?

A: To reset a computer account's Active Directory (AD) password from the command line, you can use Windows PowerShell or Netdom.exe. To reset the computer password on your local machine using PowerShell, you must use the Reset-ComputerMachinePassword cmdlet.


2 Answers

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();   } } 
like image 185
tvanfosson Avatar answered Oct 14 '22 23:10

tvanfosson


Here's a great Active Directory programming quick reference:

Howto: (Almost) Everything In Active Directory via C#

See the password reset code near the end.

public void ResetPassword(string userDn, string password) {     DirectoryEntry uEntry = new DirectoryEntry(userDn);     uEntry.Invoke("SetPassword", new object[] { password });     uEntry.Properties["LockOutTime"].Value = 0; //unlock account      uEntry.Close(); } 
like image 33
TWA Avatar answered Oct 15 '22 00:10

TWA