Setting the LastPasswordSet date for a user in Active Directory

ぐ巨炮叔叔 提交于 2019-12-08 07:18:33

问题


I want to set the LastPasswordSet attribute of a user in Microsoft Active Directory.

The .NET UserPrincipal API exposes the LastPasswordSet property as readonly.

Is there a way around this, to set the value (perhaps using ADSI)?

Edit:

MSDN provides the following example code:

usr.Properties["pwdLastSet"].Value = -1; // To turn on, set this value to 0.
usr.CommitChanges();

This forces the user to change their password at next logon. I presume if I replace -1 with a date-time in the relevant format, this will do what I want.

It does not, however, show how I get hold of the principal (presumably usr). I'll upvote anything that helps me find this out.


回答1:


Another way would be to perform a search against the AD through the DirectorySearcher class using the login of your users.

public DirectoryEntry GetUser(string domain, string loginName) {
    DirectorySearcher ds = new DirectorySearcher();
    ds.SearchRoot = new DirectoryEntry(domain);
    ds.SearchScope = SearchScope.Subtree;
    ds.PropertiesToLoad.Add("sAMAccountName");
    ds.PropertiesToLoad.Add("pwdLastSet");
    ds.Filter = string.Format("(&(objectCategory=person)(objectClass=user)(sAMAccountName={0})", loginName);

    SearchResult sr = null;

    try {
        sr = ds.FindOne();
        if (sr == null) return null;
        return sr.GetDirectoryEntry();
    } catch (Exception) {
        throw;
    }
}

Then, when wanting to set your PasswordLastSet property, you assure that the user exists and that there is no spelling mistakes.

string loginName = "AstonB1";

using(DirectoryEntry user = GetUser(loginName)) {
    if (user == null) return;

    user.Properties["pwdLastSet"].Value = whatever-format-the-date-should-be;
    user.CommitChanges();
    user.Close();
}



回答2:


Something like this?

var usr = new DirectoryEntry("LDAP://CN=Old User,CN=users,DC=fabrikam,DC=com");
usr.Properties["pwdLastSet"].Value = whatever-format-the-date-should-be;
usr.CommitChanges();

As yet untested.



来源:https://stackoverflow.com/questions/2905277/setting-the-lastpasswordset-date-for-a-user-in-active-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!