JSI Tip 9900. How can I report all enabled user accounts that have logged on within the past N days?


I have scripted ActiveUsers.bat to report the sAMAccountName and lastLogon of all enabled user accounts that have logged on within the past N days, even if you have multiple domain controllers.

NOTE: In a native Windows Server 2003 domain, the lastLogonTimeStamp attribute is replicated to all domain controller. This script assumes that the lastLogonTimeStamp attribute is NOT replicated, and retrieves the lastLogon attribute from every domain controller.

The syntax for using ActiveUsers.bat is:

ActiveUsers Days

Where user have logged on since today minus Days.

NOTE: ActiveUsers.bat uses DSQUERY, an Active Directory command-line tool, DatePorM.bat, iDateYMD.bat, and CvtFileTime, which must be located in a folder that is in your PATH.

NOTE: ActiveUsers.bat uses Bitwise filtering and NOT EQUAL filtering on userAccountControl to determine that that user account is enabled.

ActiveUsers.bat contains:

@echo off
if \{%1\}==\{\} @echo Syntax: ActiveUsers Days&goto :EOF
if %1 NEQ +%1 @echo Syntax: ActiveUsers Days&goto :EOF
setlocal
set /a days=10000%1%%10000
set qry=dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(!userAccountControl:1.2.840.113556.1.4.803:=2))" -attr lastLogon sAMAccountName -LIMIT 0
set ls=%LOGONSERVER:\=%
call DatePorM -%days% From
call iDateYMD %From% YYYY MM DD
set YYYYMMDD=%YYYY%%MM%%DD%
for /f "Skip=1 Tokens=1*" %%a in ('%qry% -s "%ls%"') do (
 set on=0
 set usr="%%b"
 call :last %%a
 for /f "Tokens=*" %%s in ('dsquery server -O RDN^|find /I /V "%ls%"') do (
  for /f "Skip=1 Tokens=1*" %%x in ('%qry% -s "%%s"') do (
   call :last %%x
  )
 )
 call :report
)
endlocal
goto :EOF
:last
if "%1" EQU "0" goto :EOF
if "%on%" LSS "%1" set on=%1
goto :EOF
:report
if "%on%" EQU "0" goto :EOF
Call CvtFileTime %on% ondt 
for /f "Tokens=1" %%i in ('@echo %ondt%') do (
 call iDateYMD %%i oldYY oldMM oldDD
)
set old=%oldYY%%oldMM%%oldDD%
if "%old%" LEQ "%YYYYMMDD%" goto :EOF
set usr=%usr:  =%
set usr=%usr: "="%
@echo %usr% %old%



Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish