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.
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.
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.
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(); } }
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With