c# - 从 ADUser 获取 UserPrincipal

标签 c# .net active-directory ldap

我有一个 ADUser 列表,但是对于每个 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 的任何属性,上面的代码也不起作用,问题是它发送了很少的电子邮件,然后在它给出的某个地方遇到了错误和服务停止,这可能是因为一些无效的日期(我不想修复它,只是为了让你了解我在做什么)

最佳答案

您可以创建自己的 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 天。

关于c# - 从 ADUser 获取 UserPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9770877/

相关文章:

c# - 通用存储库和事务

c# - StaticPagedList 以及 POST 表单 : No parameterless constructor defined for this object

javascript - 从 ASP.NET MVC 中的 AngularJS Controller 加载数据,无需加载整个页面

c# - 使用 Windows C# 应用程序将应用程序限制为 32 位架构

c# - 打开 "known file type"进入自定义应用程序的运行实例 - .NET

windows - 净用户 $userName/domain

java - 在 Java 或命令行实用程序中是否有一种方法可以使用 native SSPI API 获取服务的 Kerberos 票证?

c# - 检查响应字符串是 JSON 对象还是 XML?

.net - 为 .Net XmlDocument 实现 GetByClassName

powershell - 以特定服务器为目标时,如何让 Get-ADUser 性能更好?