How to programmatically change Active Directory password

后端 未结 6 1511
执念已碎
执念已碎 2020-11-27 14:28

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

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 14:50

    Try this code. It works for me,

    public void ChangeMyPassword(string domainName, string userName, string currentPassword, string newPassword)
    {
        try
        {
            string ldapPath = "LDAP://192.168.1.xx";
            DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainName + "\\" + userName, currentPassword);
            if (directionEntry != null)
    
            {
                DirectorySearcher search = new DirectorySearcher(directionEntry);
                search.Filter = "(SAMAccountName=" + userName + ")";
                SearchResult result = search.FindOne();
                if (result != null)
                {
                    DirectoryEntry userEntry = result.GetDirectoryEntry();
                    if (userEntry != null)
                    {
                        userEntry.Invoke("ChangePassword", new object[] { currentPassword, newPassword });
                        userEntry.CommitChanges();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    

提交回复
热议问题