Thursday, April 9, 2015

Reset a user's password in AD with C#.NET

     public void ResetUsersPassword(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
   
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string resetPasswordString = "Are you sure you want to reset " + usr.DisplayName + "'s password?";  
             yesNoDialog = MessageBox.Show(resetPasswordString, "Password Reset", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               usr.SetPassword("Password1");  
               usr.ExpirePasswordNow();  
               MessageBox.Show(usr.DisplayName + "'s password has been reset.");  
             }  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
   
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  

No comments:

Post a Comment