如何以编程方式找出计算机的上次登录时间?

esa*_*sac 3 c# monitoring login

我想a)以编程方式和b)远程找出用户成功登录Windows计算机的最后日期/时间(通过远程桌面或在控制台)。我愿意采用任何典型的Windows语言(C,C#,VB,批处理文件,JScript等),但是任何解决方案都可以。

Kol*_*ten 5

您可以使用DirectoryServices在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());
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)


Abh*_*tel 5

尝试这个:

  public static DateTime? GetLastLogin(string domainName,string userName)
  {
        PrincipalContext c = new PrincipalContext(ContextType.Domain,domainName);
        UserPrincipal uc = UserPrincipal.FindByIdentity(c, userName);
        return uc.LastLogon;
   }
Run Code Online (Sandbox Code Playgroud)

您需要添加对 using using System.DirectoryServices 和 System.DirectoryServices.AccountManagement 的引用

编辑:您可以通过执行以下操作将上次登录日期时间获取到特定机器:

 public static DateTime? GetLastLoginToMachine(string machineName, string userName)
 {
        PrincipalContext c = new PrincipalContext(ContextType.Machine, machineName);
        UserPrincipal uc = UserPrincipal.FindByIdentity(c, userName);
        return uc.LastLogon;

 }
Run Code Online (Sandbox Code Playgroud)