获取Active Directory中计算机的上次登录时间

Bag*_*Jr. 1 c# 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();
Run Code Online (Sandbox Code Playgroud)

我用ComputerPrincipal替换了UserPrincipal。名称和其他一些属性可以正常工作,但登录则不能。我尝试做不同的事情,例如将其强制转换为DateTime(强制转换失败),但没有任何效果。以上只是System .__ ComObject的结果。那么我该怎么做才能正确获取上次登录时间呢?

Sco*_*ain 5

您为什么不只使用ComputerPrincipal返回LastLogon属性?(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();
Run Code Online (Sandbox Code Playgroud)

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