JSI Tip 7694. How many times has a user (or all users) logged onto the domain?

Using the Active Directory command-line tools, in a Windows 2000 domain, or Windows Server 2003 domain, I have scripted DomainLogonCount.bat to display the distinguished name and domain logon count, using the semi-colon (;) delineated format of "Distinguished Name";"Logon Count", for one or all users.

The syntax for using DomainLogonCount.bat is:

\[call\] DomainLogonCount SamId | *

where Samid is the user name, like Jerold, or an asterisk (*) to display all users.

The output is displayed on the CMD console, but you can pipe it to a file using the following syntax:

DomainLogonCount *>FileName

You can use the output in subsequent commands, as in:

for /f "Tokens=1* Delims=;" %%i in ('DomainLogonCount *') do SomeCommand %%i %%j

DomainLogonCount.bat contains:

@echo off
if \{%1\}==\{\} @echo Syntax \[call\] DomainLogonCount SamId ^| *&exit /b 1
set user=%1
set query=dsquery * domainroot -filter "(&(objectCategory=Person)(objectClass=User)(sAMAccountName=%user%))" -attr distinguishedName logonCount -limit 0
for /f "Tokens=*" %%u in ('%query%') do set line=%%u&call :parse
exit /b 0
if /i "%line:~0,17%" NEQ "distinguishedName" goto detail
set /a pos=17
set /a pos=%pos% + 1
call set work=%%line:~%pos%^,11%%
if /i "%work%" NEQ " logonCount" goto :loop
set /a pos=%pos% + 1
set /a len=%pos% - 2
goto :EOF
call set lc=%%line:~%pos%%%
set /a lc=100000%lc%%%100000
call set dn="%%line:~0,%len%%%"
set dn=%dn:   =%
set dn=%dn:  =%
set dn=%dn: "="%
@echo %dn%;"%lc%"

Hide 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.