Skip navigation

JSI Tip 8665. How can I report all user accounts that will expires in the next N days?


Using the DSQUERY Active Directory command-line tool, DatePorM.bat, CVTFileTime.bat, Today.bat, and userAccountControl.bat, I have scripted Expires.bat to report all user accounts that will be expired in the next N days.

NOTE: Expires.bat reports account expiration, NOT password expiration.

The syntax for using Expires.bat is:

for /f "Tokens=1-3*" %%a in ('Expires Days \[/X\]') do (
 set usr=%%a
 set ExpireDT=%%b
 set ExpireTM=%%c
 set UserDN=%%d
 call :DoSomeThing
)
Where Days is a signed integer that will be added or subtracted from today's date, and /X is an optional switch that will bypass active accounts that expire before today.

The returned variables are usr, the NetBIOS user name (sAMAccountName), ExpireDT, the MM/DD/YYYY that the account expires, ExpireTM, the HH:MM:SS that the account expires on ExpireDT, and UserDN, the user's distinguished name (distinguishedName).

NOTE: Expires.bat bypassed accounts that are disabled.

Expires.bat contains:

@echo off
if \{%1\}

\{\} @echo Syntax: Expires Days \[/X\]&goto :EOF if not \{%2\}

\{\} if /i not \{%2\}

\{/X\} @echo Syntax: Expires Days \[/X\]&goto :EOF setlocal set Days=%1# if not \{%2\}

\{\} ( set exclude=Y ) ELSE ( set exclude=N ) call today MMn DDn YYn Abrev MM DD set TodayDT=%YYn%%MM%%DD% :setdays if "%days:~0,1%" EQU "0" set days=%days:~1%&goto setdays set days=%days:#=% if "%days%" EQU "" set days=0 call DatePorM %Days% MMDDYYYY set ExpYYYYMMDD=%MMDDYYYY:~6,4%%MMDDYYYY:~0,2%%MMDDYYYY:~3,2% set qry=dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User))" -attr accountExpires userAccountControl sAMAccountName distinguishedName -limit 0 for /f "Skip=1 Tokens=1-3*" %%a in ('%qry%') do ( if not "%%a" EQU "0" call :expire %%a %%b %%c "%%d" ) endlocal goto :EOF :expire call cvtfiletime %1 expdt if /i "%expdt%" EQU "Never" goto :EOF set usrdt=%expdt:~6,4%%expdt:~0,2%%expdt:~3,2% if "%usrdt%" GTR "%ExpYYYYMMDD%" goto :EOF if "%exclude%" EQU "Y" if "%usrdt%" LSS "%TodayDT%" goto :EOF call userAccountControl %2 CommaSeparatedString set dis=N for /f "Tokens=1*" %%x in ('@echo %CommaSeparatedString%^|find /I "ACCOUNTDISABLE"') do ( set dis=Y ) if "%dis%" EQU "Y" goto :EOF set dn=%4 set dn=%dn: =% set dn=%dn: "="% @echo %3 %expdt% %dn%



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