繁体   English   中英

从ADUser获取UserPrincipal

[英]Getting a UserPrincipal from ADUser

我有一个ADUsers列表,但是foreach ADUSER我想获取它的属性“ LastPasswordSet”,该属性只能通过UserPrincipal访问(不确定是否还有其他方法)。

如果我使用此代码,

 PrincipalContext l_objContext = new PrincipalContext(ContextType.Domain, l_strDomain, l_strUserOU);

 foreach (ADUser ADuser in Users)
            {
                UserPrincipal usr = UserPrincipal.FindByIdentity(l_objContext, ADuser.CommonName.ToString());

                if (usr.LastPasswordSet.HasValue)
                {
                    EmailString(usr.LastPasswordSet.ToString());
                }
            }

现在,我不想将任何东西提供给UserPrincipal,然后再将ADUSER的任何属性都提供给UserPrincipal,并且上面的代码也不起作用,问题是它发送的电子邮件很少,然后碰到它给出的某处,并且错误和服务停止,这可能是由于某个无效的日期(我不想修复它,只是说了一下,以便您了解我在做什么)

您可以创建自己的PrincipalContext ,然后使用UserPrincipal.FindByIdentity获取主体。 我怀疑您已经从这里开始,可以调用LastPasswordSet属性。

public static DateTime? GetLastPasswordSet(string domain, string userName)
{
    using (var context = new PrincipalContext(ContextType.Domain, domain))
    {
        var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
        return userPrincipal.LastPasswordSet;
    }
}

注意:您将需要添加对System.DirectoryServices.AccountManagement的引用

[ 编辑 :回应评论中的其他问题]

要测试密码是否是一个月前最后一次设置-像这样:

if (lastPasswordSet < DateTime.Now.AddMonths(-1))
{
   // Password last set over a month ago.
}

要记住的一件事是,一个月的时间长度含糊不清-它的长度取决于您所在的月份(和年份)。根据您要执行的操作,固定时间段可能更适合例如28天。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM