Hello all. I need a little help. I have a script, see below, that searches all my domain controllers and populates a list of all users and tells me their last logon dates, giving me the most recent of the 2 dates (which is what I need). HOWEVER. It shows
me users who have never logged on as well and gives them a date of 1/1/1900. I need to modify this script so that it excludes users who have never logged in and can exclude accounts I don't want to search for. I also then need it to only give me users who
have not logged in for 30 days or more. I have tried modifying the search.filter tag and nothing seems to work for me. Please help. Thank you.
Trap {"Error: $_"; Break;}
$D = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$Domain = [ADSI]"LDAP://$D"
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.PageSize = 200
$Searcher.SearchScope = "subtree"
# Switch this to search for computers or users
#$Searcher.Filter = "(&(objectCategory=computer))"
$Searcher.Filter = "(&(objectCategory=user))"
$Searcher.PropertiesToLoad.Add("distinguishedName") > $Null
$Searcher.PropertiesToLoad.Add("lastLogon") > $Null
# Create hash table of users and their last logon dates.
$arrUsers = @{}
# Enumerate all Domain Controllers.
ForEach ($DC In $D.DomainControllers)
{
$Server = $DC.Name
$Searcher.SearchRoot = "LDAP://$Server/" + $Domain.distinguishedName
$Results = $Searcher.FindAll()
ForEach ($Result In $Results)
{
$DN = $Result.Properties.Item("distinguishedName")
$LL = $Result.Properties.Item("lastLogon")
If ($LL.Count -eq 0)
{
$Last = [DateTime]0
}
Else
{
$Last = [DateTime]$LL.Item(0)
}
If ($Last -eq 0)
{
$LastLogon = $Last.AddYears(1600)
}
Else
{
$LastLogon = $Last.AddYears(1600).ToLocalTime()
}
If ($arrUsers.ContainsKey("$DN"))
{
If ($LastLogon -gt $arrUsers["$DN"])
{
$arrUsers["$DN"] = $LastLogon
}
}
Else
{
$arrUsers.Add("$DN", $LastLogon)
}
}
}
# Output latest last logon date for each user.
$Users = $arrUsers.Keys
ForEach ($DN In $Users)
{
$Date = $arrUsers["$DN"]
If ($Date -eq "01/01/1601 00:00:00") {$Date = "1/1/1900 12:00:00"}
$DN = [regex]::Match($DN,'CN=([^,]+)').Groups[1].Value
"`"$DN`", $Date"
}