How to programatically find out the last login time to a machine?

前端 未结 5 974
天涯浪人
天涯浪人 2020-12-18 12:08

I would like to a) programatically and b) remotely find out the last date/time that a user successfully logged into a Windows machine (via remote desktop or at the console).

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 12:46

    You can use DirectoryServices to do this in C#:

    using System.DirectoryServices;
    
            DirectoryEntry dirs = new DirectoryEntry("WinNT://" + Environment.MachineName);
            foreach (DirectoryEntry de in dirs.Children)
            {
                if (de.SchemaClassName == "User")
                {
                    Console.WriteLine(de.Name);
                    if (de.Properties["lastlogin"].Value != null)
                    {
                        Console.WriteLine(de.Properties["lastlogin"].Value.ToString());
                    }
                    if (de.Properties["lastlogoff"].Value != null)
                    {
                        Console.WriteLine(de.Properties["lastlogoff"].Value.ToString());
                    }
                }
            }
    

提交回复
热议问题