'
' Lists users of a domain with the domain controller last used to log in, and the date/time of the
' last login. Outputs results to console in comma seperated format. Useful to pipe output to a file
' for loading in a spreadsheet. (cscript adtool-users.vbs > userlist.csv)
'
' Change these for your domain
domain = "dc=web,dc=mycompany,dc=net"
domain2 = "web.mycompany.net"

Dim oUsers,oDCList,ObjConnection,objCommand,domain,domain2
Set ObjConnection = CreateObject("ADODB.Connection")
ObjConnection.Open "Provider=ADsDSOObject;"
Set objCommand = CreateObject("ADODB.Command")
objCommand.ActiveConnection = ObjConnection

category = "user" ' should also work for computer accounts, but doesn't

getDCs()    ' sets up oDCList
getAccounts()    ' sets up oUsers
While Not oUsers.EOF
    getLastDate(oUsers.Fields("sAMAccountName"))
    oUsers.MoveNext
Wend

WScript.Quit()


Function getDCs()
    Set oDCList=GetObject("LDAP://OU=Domain Controllers," & domain) 'DN for Domain Controllers
'    WScript.Echo("Domain controllers are:")
'    For Each DCName In oDCList
'        WScript.Echo("    " & DCName.name)
'    Next    
End Function


Function getAccounts()
    objCommand.CommandText = "<LDAP://" & domain & ">;(objectCategory=" & category & ");sAMAccountName;subtree"
    Set oUsers = objCommand.Execute
End Function


Function getLastDate(name)
On Error Resume Next ' blank LastLogin causes error
    newestDate = 0
    result = name & ",-,never"
    For Each DCName In oDCList
        dc = Right(DCName.name,(Len(DCName.name)-3)) ' Remove the "CN=" from dc names
        Set oComp = GetObject("WinNT://" & dc & "." & domain2 & "/" & name & "," & category)
        If Err.Number <> 0 Then
            Err.Clear()
        End If
        If oComp.LastLogin > newestDate Then
            newestDate = oComp.LastLogin
            result = name & "," & dc & "," & oComp.LastLogin
        End if
    Next
    WScript.Echo(result)
On Error goto 0
End function