In this post we'll talk about Disable-Inactive-ADAccounts, a small yet useful Powershell script that can be used by System Administrators to perform the following tasks:
- Disable all the Active Directory user accounts inactive for more than X days
- Delete all the Active Directory user accounts prevously disabled more than Y days ago.
The two above tasks can be run independently using the provided command-line switches.
Why should we do that?
As a matter of fact, being able to automatically disable AD accounts after X days of inactivity is a good security practice. If you don't have such process up, your Active Directory could grant "permanent" access to many user accounts that should no longer be active, such as those of ex-employees or collaborators who are no longer active at your company.
Unfortunately, such feature is not (yet) supported by any version of Windows or Windows Server, at least up to Windows 10 and Windows Server 2019. That's why we ended up to develop this Powershell script.
Usage
To disable all AD users that has been inactive for 180 days or more (without deleting them):
> powershell .\Disable-Invalid-ADAccounts.ps1 -days 180
Same thing as before, plus creating a logFile.csv file containing a list of all disabled users:
> powershell .\Disable-Invalid-ADAccounts.ps1 -days 180
To disable all AD users that has been inactive for 180 days or more and also delete those that have been previously disabled more than 180 days ago.
> powershell .\Disable-Invalid-ADAccounts.ps1 -days 180 -deleteDays 180
Same thing as before, plus creating a logFile.csv file containing a list of all disabled users and a deleteLogFile.csv file containing a list of all deleted users:
powershell .\Disable-Invalid-ADAccounts.ps1 -days 180
In case you get permissions issues when disabling/deleting AD users, you can bypass them using the Bypass Execution Policy Flag in the following way:
powershell -ExecutionPolicy Bypass -File Disable-Invalid-ADAccounts.ps1
The Code
Here's the full script source code:
As you can see there are a lot of in-line comments, thus making the above code quite self-explanatory: however, if you got questions, feel free to ask anything using the comments section below this post.
Conclusion
That's about it: if you like this script, feel free to give me a virtual hug by starring the GitHub project and/or putting a like on our Facebook/Twitter pages!