Active Directory Cleanup

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of Anton Pozdnyakov Anton Pozdnyakov 3 weeks, 1 day ago.

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #51751
    Profile photo of Justin Dietz
    Justin Dietz
    Participant

    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.

    #51765
    Profile photo of Dan Potter
    Dan Potter
    Participant

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

    #53472
    Profile photo of Anton Pozdnyakov
    Anton Pozdnyakov
    Participant

    Have a look at this article for a fully done AD cleanup PowerShell solution: https://powershell.org/forums/topic/active-directory-cleanup/

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

    #53499
    Profile photo of Anton Pozdnyakov
    Anton Pozdnyakov
    Participant

    Sorry, gave the wrong link, here's a correct one: http://www.adaxes.com/blog/cleanup-active-directory-with-powershell.html

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.