Reset Password

Below is the code necessary to set a new password for a user in the Active Directory.
Of course the person running the program needs administrator rights to do it.

Console.WriteLine("USERNAME:");
String strUserName = Console.ReadLine();
Console.WriteLine("PASSWORD:");
String strPassword = Console.ReadLine();

try{
    Console.Write("START...");

    String strPath = "LDAP://dc=myDomainName";
    DirectoryEntry de = new DirectoryEntry(strPath);
    DirectorySearcher ds = new DirectorySearcher(de);

    // filter result
    ds.Filter = "(&(objectClass=user)(|(sAMAccountName=" + strUserName + ")))";

    // LOAD PROPERTIES
    ds.PropertiesToLoad.Add("displayName");
    ds.PropertiesToLoad.Add("sAMAccountName");
    ds.PropertiesToLoad.Add("DistinguishedName");
    ds.PropertiesToLoad.Add("CN");

    // LOAD INTO LDAP RETURN STRING
    SearchResult result = ds.FindOne();

    String dn = result.Properties["DistinguishedName"][0].ToString();
    String sam = result.Properties["sAMAccountName"][0].ToString();

    de.Close();

    // set new password
    DirectoryEntry uEntry = new DirectoryEntry(dn);
    uEntry.Path = dn;
    uEntry.AuthenticationType = AuthenticationTypes.Secure;

    object[] pass = new object[] { strPassword };
    uEntry.Invoke("SetPassword", pass);
    uEntry.Properties["LockOutTime"].Value = 0; //unlock the account
    uEntry.CommitChanges();
    uEntry.Close();

    Console.Write("COMPLETED");
}
catch(Exception e){
    Console.WriteLine("Error:" + e.Message);
}
Console.WriteLine("END");
Console.ReadLine();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License