Active Directory Cleanup

Welcome Forums General PowerShell Q&A Active Directory Cleanup

This topic contains 3 replies, has 3 voices, and was last updated by

2 years, 6 months ago.

  • Author
  • #51751

    Points: 0
    Rank: Member

    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

    Points: 21
    Rank: Member

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

  • #53472

    Points: 0
    Rank: Member

    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.

  • #53499

    Points: 0
    Rank: Member

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

The topic ‘Active Directory Cleanup’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort