Inactive Active Directory (AD) user accounts can pose a security risk to organizations, in situations such as when former employees still have active accounts months after leaving the company because HR failed to inform IT, or accounts might be created for a particular purpose but never deleted after the event. Whatever the reason for the existence of such accounts, Active Directory can quickly get out of control, in turn making your systems harder to audit and less secure.
Active Directory Module for Powershell
The PowerShell module for Active Directory allows system administrators to query Active Directory and generate reports using the resulting data. The AD module for PowerShell is installed by default on Windows Server 2012/16/19/22 domain controllers, or alternatively, you can download the Remote Server Administration Tools (RSAT) and install the module using the command below.
Log in as a local administrator, open a PowerShell prompt, type the code below, and press ENTER to install the AD module for PowerShell:
Search Active Directory for Inactive Accounts
The Search-ADAccount cmdlet provides an easy way to query Active Directory for inactive user accounts:
Search-ADAccount –UsersOnly –AccountInactive
The above command returns all inactive accounts. To narrow down the results to a specific time range, you can add the –TimeSpan parameter to Search-ADAccount. In the example below, a variable defines the value for the –TimeSpan parameter, using the New-Timespan cmdlet to simplify the input:
$timespan = New-Timespan –Days 90 Search-ADAccount –UsersOnly –AccountInactive –TimeSpan $timespan
To get more user-friendly information about the accounts, pipe the results to the Get-ADUser cmdlet and then choose the columns to display in the output using Select:
Search-ADAccount –UsersOnly –AccountInactive | Get-ADuser -Properties Department,Title | Select Name,Department,Title,DistinguishedName
The results can also be sorted by a specified field, in this example by the LastLogOnDate attribute, which is derived from the LastLogonTimestamp and converted into a readable format:
Search-ADAccount –UsersOnly –AccountInactive | Get-ADuser -Properties Department,Title | Sort LastLogOnDate | Select Name,Department,Title,DistinguishedName
It’s worth noting that, unlike the LastLogOn attribute, LastLogonTimestamp is synchronized between domain controllers but can be 9 to 14 days out-of-date, so you should bear this in mind when processing your results.
Disable Inactive Accounts
Once you’ve got the set of results you’re looking for, all you need to do is pipe them to the Disable-ADAccountcmdlet as shown here to disable the accounts:
Search-ADAccount –UsersOnly –AccountInactive –TimeSpan $timespan | Disable-ADAccount
That’s all folks.