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

Getting last Logon Time on Computers in Active Directory(在 Active Directory 中的计算机上获取上次登录时间)

本文介绍了在 Active Directory 中的计算机上获取上次登录时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取活动目录中的用户?

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

Please see the page above. It answered most of my questions, but I get a problem when I try to get last logon time for a computer. Sorry if there was some way to comment on that page instead of making a whole new question because I didn't find such an option.

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.那么我该怎么做才能让它正确获得上次登录时间?

I replaced UserPrincipal with ComputerPrincipal. Name and some other properties work fine, but logon doesn't. I've tried doing different things like casting it to DateTime (the cast failed) but nothing worked. The above just results in System.__ComObject. So what can I do to get it to get last logon time correctly?

推荐答案

为什么不直接使用 ComputerPrincipal 返回的LastLogon 属性?(ComputerPrincipal 是一个 AuthenicatablePrincipal)

Why aren't you just using the the LastLogon property returned by ComputerPrincipal? (ComputerPrincipal is a 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 不是复制属性,因此如果您有多个域控制器,则需要查询每个控制器并找出谁给出了最新的结果.

Note that LastLogon is not a replicated property, so if you have more than one domain controller you need to query each controller and find out who gives the most recent result.

这篇关于在 Active Directory 中的计算机上获取上次登录时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 Active Directory 中的计算机上获取上次登录时间

基础教程推荐