Home > Net >  Looking for a way to get Active Directory user accounts with logons less than 90 days
Looking for a way to get Active Directory user accounts with logons less than 90 days

Time:06-03

So far I tried this** Does not seem to work well, I get dates back from 2014. And only a few from 2022

$90Days = (get-date).adddays(-90)
Get-ADUser -SearchBase "OU=Domain Users,DC=x,DC=state,DC=x,DC=x" -properties * -filter {(lastlogondate -notlike "*" -OR lastlogondate -le $90days) -AND (passwordlastset -le $90days)} | select-object name, SAMaccountname, lastlogondate | export-csv c:\Temp\90days.csv

CodePudding user response:

It's a simple flip from less than to greater than. Dates are stored as numbers that increment every millisecond. Starting at a date 90 days ago and asking for "less than" means get everything from 90 days ago and earlier, not 90 days and greater to "today".

Simply flip your -le to -ge.

$90Days = (get-date).adddays(-90)
Get-ADUser -SearchBase "OU=Domain Users,DC=x,DC=state,DC=x,DC=x" -properties * -filter {(lastlogondate -notlike "*" -OR lastlogondate -ge $90days) -AND (passwordlastset -ge $90days)} | select-object name, SAMaccountname, lastlogondate | export-csv c:\Temp\90days.csv

CodePudding user response:

Your filter is wrong. lastlogondate -notlike "*" -OR literally means if LastLogonDate not like anything OR ... This means it would almost always pass the test.

Then, I don't see why you also include property PasswordLastset in the equation as your question is not about that.

I think this would work better for you:

$90Days = (Get-Date).AddDays(-90).Date  # set the date to midnight 

Get-ADUser -SearchBase "OU=Domain Users,DC=x,DC=state,DC=x,DC=x" -Filter "Enabled -eq $true -and LastLogonDate -ge $90Days" -Properties LastLogonDate | 
    Select-Object Name, SamAccountName, LastLogonDate | 
    Export-CSV -Path 'c:\Temp\90days.csv' -NoTypeInformation

P.S. Don't ask for ALL properties with -Properties * if you only want one extra property on top of the attributes returned by default like Name and SamAccountName.

Please also bear in mind that the calculated property LastLogonDate (not really a AD attribute at all) is not replicated within the domain and to get the most accurate value, you need to iterate the domaincontrollers in your domain.

  • Related