Disable AD users in specific OU after X days with powershell script

Marko Todorovic 61 Reputation points
2021-06-24T14:53:35.96+00:00

Hi all, I need your help as I'm not proficient with Powershell enough to create this kind of script on my own.

I would like to disable all users of a specific OU that haven't logged in for more than X days (let's say 5 for example).
There are no service accounts in it, so only regular users.
Also, there is no need for the script to write reason for disabling in the description field as I've seen in some examples.
So only, a script that imports active directory module, target's the specified OU, checks if the logon date is above that number of days and disables them.

The setup could be like this:
Domain: random.local
Targeted OU: random/random users and groups/random users

Thanks a lot in advance for any help on this!

Regards,
Marko

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,389 questions
0 comments No comments
{count} votes

Accepted answer
  1. Andreas Baumgarten 97,566 Reputation points MVP
    2021-06-24T15:10:20.397+00:00

    Hi @Marko Todorovic ,

    maybe this helps to get started (Use on your own risk! Not tested by myself.):

    $searchBase = "OU=random,DC=random,dc=local"  
    Search-ADAccount -SearchBase $searchBase -UsersOnly -AccountInactive -TimeSpan ([timespan]5d)  
        | Set-ADUser -Enabled $false  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten


1 additional answer

Sort by: Most helpful
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 30,376 Reputation points Microsoft Vendor
    2021-06-25T02:38:02.113+00:00

    Hi,

    You may try this.

    $ou= "OU=random ,DC=random ,DC=local"  
    $date = ([datetime]::Now).AddDays(-5)  
    Get-ADUser -SearchBase $ou -Filter {lastlogon -lt $date} | Set-ADUser -Enabled $False  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments