JSI Tip 8244. How do I retrieve the last log on and last log off date and time for a user, even if they were authenticated by different domain controllers?

Jerold Schulman

July 11, 2004

1 Min Read
ITPro Today logo

The lastLogon and lastLogoff attributes of a user are recorded on the the domain controller that authenticates them, and are NOT replicated to other domain controllers.

I have scripted LastLogOnOff.bat to return the formatted lastLogon and lastLogoff attributes of a user.

The syntax for using LastLogOnOff.bat is:

[call] LastLogOnOff UserName on off

where:

UserName is the NetBIOS User name.on       is a call directed environment variable that will contain the last log on date and time.off      is a call directed environment variable that will contain the last log off date and time.

Example:

call LastLogOnOff %UserName% timeOn timeOff
@echo %UserName% logged on at %timeOn% and logged off at %timeOff%.

Might display:

Jerry logged on at 07/06/2004 07:27:43 and logged off at Never.

NOTE: LastLogOnOff.bat use DSQUERY and CvtFileTime.bat.

LastLogOnOff.bat contains:

@echo offif {%3}=={} @echo Syntax: LastLogOnOff UserName on off&goto :EOFsetlocalset user=%1set qry=dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=%user%))" -attr lastLogon lastLogoff -limit 0set on=0set off=0for /f "Tokens=*" %%s in ('dsquery server -O RDN') do ( for /f "SKIP=1 Tokens=1,2" %%a in ('%qry% -s "%%s"') do ( call :last %%a %%b ))Call CvtFileTime %on% ondtCall CvtFileTime %off% offdtendlocal&set %2=%ondt%&set %3=%offdt%goto :EOF:lastif "%on%" LSS "%1" set on=%1if "%off%" LSS "%2" set off=%2



Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like