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). I would be willing to take any typical windows language (C, C#, VB, batch files, JScript, etc...) but any solution would be nice.
+1
A:
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());
}
}
}
Kolten
2009-09-24 21:41:28
Great answer, any chance you would know how to modify it to include domain users such as MYDOMAIN or at least a specific domain user such as MYDOMAIN\MYUSER?
esac
2009-09-24 22:17:42
+1
A:
Try this:
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 references to using using System.DirectoryServices and System.DirectoryServices.AccountManagement
EDIT: You might be able to get the last login Datetime to 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;
}
Abhijeet Patel
2009-09-25 01:57:19
Does that give the last login to the domain, or to the computer it is run on?
esac
2009-09-25 03:35:25
Good question.MSDN says this: "Gets the Nullable DateTime that specifies the date and time of the last logon for this account."I'm guessing that this is based on whether the ContextType is set to Domain or Machine but I can't verify this since I'm running on a standalone machine but an my educated guess is that if you are running on a domain it probably the last successful logon for that account on the domain.
Abhijeet Patel
2009-09-26 00:24:07
Darn, I like both of your answers, but I really need the last login time of a specific user to the specified computer.
esac
2009-09-27 05:55:53
I think I might have found a way, I've edited my answer. Again I can't verify this since I'm not on a domain.
Abhijeet Patel
2009-09-28 06:10:29