question

MarkoTodorovic-7973 avatar image
0 Votes"
MarkoTodorovic-7973 asked MarkoTodorovic-7973 commented

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

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AndreasBaumgarten avatar image
0 Votes"
AndreasBaumgarten answered MarkoTodorovic-7973 commented

Hi @MarkoTodorovic-7973 ,

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
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hey, thanks a lot. It works. I've tested with 5 test users (where with 1 I logged in previously and other 4 I didn't) and after executing script, it disabled those 4 and didn't disable the 1 it detected login activity. Thanks a lot for your help!

0 Votes 0 ·
IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.