Report - Last Logon User from Active Directory
Hello Guys,
The objective of keeping the base clean Active Directory, follow the script to generate a report of the last logon of users from Active Directory, so it is possible to identify and delete the user who log on the network to more than 1 year.
Save the following script as *. VBS and use the complete script execution will generate a *. csv file.
___________________________
Option Explicit
Dim strDomain, strOU
strDomain = "Contoso.corp"
strOU = "DC=contoso,DC=corp"
strDomain = InputBox("Enter the FQDN of the domain to be searched." & chr(13)& chr(13) & "Exemplo: " & chr(13) & "contoso.corp", "Domain to be searched", strDomain)
If strDomain = "" Then wscript.quit
strOU = InputBox("Enter the LDAP path of the container to be searched." & chr(13) & chr(13)& "Exemplos: " & chr(13) & "DC=contoso,DC=corp" & chr(13) & "DC=contoso,DC=corp", "LDAP path to be searched", strOU)
If strOU = "" Then wscript.quit
Const ForAppending = 8
Dim k
Dim sDCs() 'Dynamic array to hold the path for all DCs
Dim BiasKey 'Active Time Bias from Registry
Dim Bias 'Time Bias
Dim strAdsPath 'Machine account DN
Dim dtmDate 'Date output string
Dim objDate
Dim sDate 'Local machine current date
Dim lngDate 'LastLogon date
Dim strTime 'Local machine current time
Dim strLDate 'Local machine current date and time
Dim objList 'Dictionary object to track latest LastLogon for each computer
Dim objRoot 'RootDSE object
Dim strConfig 'Configuration Naming Context
Dim objDC 'Domain Controller
Dim strDNSDomain 'Default nameing context
Dim strComputer 'Computer object Name
Dim objConnection 'ADO conection
Dim objCommand 'ADO command:
Dim objRecordSet 'Object to hold attributes from AD
Dim oWshShell 'Windows shell script
Dim objFSO 'File System object
Dim objFile 'File object used to open text file for output
Dim objLastLogon 'Last Logon Long Integer attribute
Dim strFilePath 'Path to current directory
Dim d
Dim lngHigh
Dim lngLow
Dim objdisplayName 'File DisplayName'
Set oWshShell = CreateObject("Wscript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
strFilePath = objFSO.GetAbsolutePathName(".")
sDate = Date
strTime = Now
StrLDate = DatePart("m",sDate) & "." & DatePart("d",sDate) & "." & Hour(strTime) & "." & Minute(strTime)
Set objFile = objFSO.OpenTextFile (strFilePath & "\report." & strLDate & ".csv",ForAppending,True)
'Use a dictionary object to track latest LastLogon for each computer.
Set objList = CreateObject("Scripting.Dictionary")
objList.CompareMode = vbTextCompare
'Obtain local Time Zone bias from machine registry.
BiasKey = oWshShell.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
If UCase(TypeName(BiasKey)) = "LONG" Then
Bias = BiasKey
ElseIf UCase(TypeName(BiasKey)) = "VARIANT()" Then
Bias = 0
For k = 0 To UBound(BiasKey)
Bias = Bias + (BiasKey(k) * 256^k)
Next
End If
'Determine configuration context and DNS domain from RootDSE object.
Set objRoot = GetObject("LDAP://RootDSE")
strConfig = objRoot.Get("ConfigurationNamingContext")
strDNSDomain = objRoot.Get("DefaultNamingContext")
'wscript.echo strDNSDomain
'Use ADO to search Active Directory for ObjectClass nTDSDSA.
'This will identify all Domain Controllers.
Set objCommand = CreateObject("ADODB.Command")
Set objConnection = CreateObject("ADODB.Connection")
objConnection.Provider = "ADsDSOObject"
objConnection.Open = "Active Directory Provider"
objCommand.ActiveConnection = objConnection
objCommand.CommandText = "<LDAP://" & strConfig & ">;(ObjectClass=nTDSDSA);AdsPath;subtree"
objCommand.Properties("Page Size") = 100
objCommand.Properties("Timeout") = 30
objCommand.Properties("Searchscope") = 2
objCommand.Properties("Cache Results") = False
Set objRecordSet = objCommand.Execute
'Enumerate parent objects of class nTDSDSA. Save Domain Controller
'AdsPaths in dynamic array sDCs.
Dim iTest1, iTest2
k = 0
Do Until objRecordSet.EOF
Set objDC = GetObject(GetObject(objRecordSet.Fields("AdsPath")).Parent)
'wscript.echo objDC.DNSHostName
iTest1 = Instr(objDC.DNSHostName, strDomain )
if iTest1 > 0 then iTest2 = InStr(Left(objDC.DNSHostName,iTest1-2),".")
'wscript.echo objDC.DNSHostName
'if iTest1 > 0 then wscript.echo "iTest1 = " & iTest1 & "[" & Left(objDC.DNSHostName,iTest1-2) & "]"
'wscript.echo "iTest2 = " & iTest2
If iTest1 > 0 And iTest2 = 0 Then
ReDim Preserve sDCs(k)
sDCs(k) = objDC.DNSHostName
'wscript.echo objDC.DNSHostName
k = k + 1
end if
objRecordSet.MoveNext
Loop
'wscript.echo
'Retrieve LastLogon attribute for each computer on each Domain Controller.
For k = 0 To Ubound(sDCs)
'wscript.echo "Checking domain controller " & sDCs(k) & ". DC " & k & " of " & Ubound(sDCs)
objCommand.CommandText = "<LDAP://" & sDCs(k) & "/" & strOU & ">;(ObjectCategory=user);Name,codepage,lastLogon,distinguishedName;subtree"
'wscript.echo "<LDAP://" & sDCs(k) & "/" & strOU & ">;(ObjectCategory=user);Name,displayname,lastLogon,distinguishedName;subtree"
On Error Resume Next
Set objRecordSet = objCommand.Execute
If Err.Number <> 0 Then
wscript.echo "Domain Controller not available: " & sDCs(k),2,"Notice",48
Err.Clear
Else
Do Until objRecordSet.EOF
'wscript.echo "Estoy aqui"
'strAdsPath = objRecordSet.Fields("Name")
strAdsPath = objRecordSet.Fields("distinguishedName")
objdisplayName = ObjRecordSet.Fields("displayName")
lngDate = objRecordSet.Fields("LastLogon")
If Not IsNull(lngDate) Then
Set objDate = lngDate
lngHigh = objDate.HighPart
lngLow = objDate.LowPart
If lngLow < 0 Then
lngHigh = lngHigh + 1
End If
If (lngHigh = 0) And (lngLow = 0 ) Then
dtmDate = #1/1/1601#
Else
: dtmDate = #1/1/1601# + (((lngHigh * (2 ^ 32)) + lngLow)/600000000 - Bias)/1440
End If
Else
dtmDate = #1/1/1601#
End If
If objList.Exists(strAdsPath) Then
If (dtmDate > objList(strAdsPath)) Then
objList(strAdsPath) = dtmDate
End If
Else
objList.Add strAdsPath, dtmDate
End If
objRecordSet.MoveNext
Loop
End If
Next
'Output latest LastLogon date for each computer.
'On Error Resume Next
objFile.WriteLine "Nome;NomeCompleto;Descrição;Última Autenticação;OU"
For Each strComputer In objList
Call VBOut(strComputer,objList(strComputer))
Next
On Error Goto 0
'objFile.WriteBlankLines (3)
objFile.Close
wscript.echo "Output file " & strFilePath & "\report." & strLDate & ".csv created."
wscript.echo "Script processing complete."
'Clean up.
Set objRoot = Nothing
Set objConnection = Nothing
Set objCommand = Nothing
Set objRecordSet = Nothing
Set objDC = Nothing
Set lngDate = Nothing
Set objList = Nothing
Set oWshShell = Nothing
Function VBOut(strPC,strTime)
Dim strComputerName 'Formatted computer name output string
Dim strOU
strComputerName = mid(strPC, 4,Instr(strPC,",")-4)
strOU = right(strPC, len(strPC)-len("CN=" & strComputerName)-1)
objFile.WriteLine strComputerName & ";" & GetADInfo(strPC) & ";" & strTime & ";" & strOU
End Function
Function GetADInfo (sMachineName)
Dim objComputer, sSO, sSP
'wscript.echo "LDAP://" & sMachineName
Set objComputer = GetObject ("LDAP://" & sMachineName)
sSO = objComputer.displayName
sSP = objComputer.description
GetADInfo = sSO & ";" & sSP
Set objComputer = Nothing
End Function
______________________________________________________________________________________________________
Thanks,
Josué Vidal
Microsoft MVP - Active Directory
MCSA | MCSE | MCT