c# - 在 Active Directory 中的计算机上获取上次登录时间

标签 c# active-directory

How can I get a list of users from active directory?

请参阅上面的页面。它回答了我的大部分问题,但是当我尝试获取计算机的上次登录时间时遇到问题。抱歉,如果有某种方法可以在该页面上发表评论而不是提出一个全新的问题,因为我没有找到这样的选项。

using (var context = new PrincipalContext(ContextType.Domain, "cat.pcsb.org"))
        {
            using (var searcher = new PrincipalSearcher(new ComputerPrincipal(context)))
            {
                foreach (var result in searcher.FindAll())
                {
                    DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
                    Console.WriteLine("Name: " + de.Properties["name"].Value);
                    Console.WriteLine("Last Logon Time: " + de.Properties["lastLogon"].Value);
                    Console.WriteLine();
                }
            }
        }
        Console.ReadLine();

我用 ComputerPrincipal 替换了 UserPrincipal。名称和其他一些属性工作正常,但登录不行。我试过做不同的事情,比如将它转换为 DateTime(转换失败),但没有任何效果。以上只是导致 System.__ComObject。那么我该怎么做才能让它正确获得上次登录时间?

最佳答案

为什么不直接使用 LastLogon property returned by ComputerPrincipal ? (ComputerPrincipal 是一个 AuthenicatablePrincipal)

using (var context = new PrincipalContext(ContextType.Domain, "cat.pcsb.org"))
{
    using (var searcher = new PrincipalSearcher(new ComputerPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            var auth = result as AuthenticablePrincipal;
            if(auth != null)
            {
                Console.WriteLine("Name: " + auth.Name);
                Console.WriteLine("Last Logon Time: " + auth.LastLogon);
                Console.WriteLine();
            }
        }
    }
}
Console.ReadLine();

请注意,LastLogon 不是复制属性,因此如果您有多个域 Controller ,则需要查询每个 Controller 并找出谁给出了最新的结果。

关于c# - 在 Active Directory 中的计算机上获取上次登录时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19454162/

相关文章:

c# - 将元素添加到列表的递归方法

c# - 使用 C# 在 Active Directory 中移动对象

azure - 如何将任何 Azure Active Directory (AD) 用户登录到连接到 Office 365 Sharepoint Online API 的共享 native 应用程序

c# - SignalR 用于高频消息传递的性能

c# - ASP.NET 正则表达式 -validationExpression

c# - 不要在应用程序洞察中记录静态文件的遥测数据

java - Apache 目录 API 拒绝将用户添加到 Active Directory "(UNWILLING_TO_PERFORM)"

ubuntu - Ubuntu已连接AD,但无法登录

active-directory - Tridion 中的配置更改以便与事件目录交互

c# - 域对象命名类的命名实践