Active Directory Cleanup

I have been tasked with running a scheduled task weekly that targets all of our different USER OUs in AD. What has to happen is powershell must search for accounts which have been INACTIVE for 90 days.

I had my work complete but when we ran it we realized that accounts that were created 20 days ago, but the user just hasn’t started yet and never logged on were also being disabled and moved.

I have found a way to get around this but figuring there has to be a cleaner way. Here is what i have so far

$checktime = (get-date).adddays(-90)
$targetOU = “OU=users ou I’m targeting,DC=Contoso,DC=ORG”
$disabledOU = OU=Disabled Accounts,DC=Contoso,DC=ORG"

#find AD user accounts that have been inactive for “x” days and then disable those accounts
Search-ADAccount -SearchBase $targetOU -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly | Set-ADUser -Enabled $false -Homepage ‘90 day inactivity-DISABLED’

#move disabled user accounts to disabled users OU
Search-ADAccount -AccountDisabled -UsersOnly -SearchBase $targetOU | Move-ADObject -TargetPath $disabledOU

#Then check the Disabled Accounts OU for anything created in the last 90 days, enable it and move it back.
get-aduser -searchbase $disabledOU -Properties whencreated -filter {whencreated -ge $checktime} | Set-ADUser -Enabled $true | move-object -targetpath $targetOU

There has to be an easier way. I would like my script to check the target ou. Find accounts inactive for 90 days **but exclude accounts that have been created in the past 90 days and the attribute lastlogontimestamp to be empty such as **get-aduser -f {-not ( lastlogontimestamp -like "")} ** then disable those results and move them to the $disabledOU

Can someone help me put this all together.

As search-adaccount doesn’t return whencreated you must use get-aduser and filter lastlogondate and whencreated.

Have a look at this article for a fully done AD cleanup PowerShell solution:

Maybe you’ll be able to either use it or take parts of it.

Sorry, gave the wrong link, here’s a correct one: