How to programmatically find out the last login time?

I would like a) programmatically and b) remotely find out the last date / time when the user successfully logged into Windows (via remote desktop or on the console). I would like to take any typical Windows language (C, C #, VB, batch files, JScript, etc.), but any solution would be nice.

+3
source share
5 answers

Try the following:

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

You will need to add usage references using System.DirectoryServices and System.DirectoryServices.AccountManagement

EDIT: you could get the latest Datetime login time on a specific machine by doing something like this:

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

 }
+4
source

DirectoryServices #:

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());
                }
            }
        }
+4

CMD:

C:\Windows\System32>query user /server:<yourHostName>

()

C:\Windows\System32>quser /server:<yourHostName>

:

USERNAME    SESSIONNAME    ID    STATE    LOGONTIME
userXYZ     console         1    Active   19.01.2017 08:59
0

PowerShell script, ACTUAL .... MICROSOFT , , , ... !

$REMOTEMACHINE = "LoCaLhOsT"

$NetLogs = Get-WmiObject Win32_NetworkLoginProfile -ComputerName $REMOTEMACHINE
foreach ($NetLog in $NetLogs) 
{ 
  if($NetLog.LastLogon)
  {
    $LastLogon = [Management.ManagementDateTimeConverter]::ToDateTime($NetLog.LastLogon)
    if($LastLogon -ne [DateTime]::MinValue)
    {
      Write-Host $NetLog.Name ' - ' $LastLogon
    }
  }
}

. , , Win32_NetworkLoginProfile "Win32API | Network Management Structures | USER_INFO_3". , # pInvoke [NetUserEnum] , , , WMI.

Fun Fact: DateTime Int32 USER_INFO_3, , 2038 , , .... #UnixMillenniumBug

0

pInvoke "RegQueryInfoKey" # LastWriteTime , "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"

fooobar.com/questions/1718505 / ...

0
source

Source: https://habr.com/ru/post/1718501/


All Articles