Over time, an organization's Active Directory (AD) network can start accumulating inactive user accounts. These accounts can be of employees who may have left the organization, temporary accounts, etc. The problem here is that these inactive AD accounts are easier targets for attackers as these accounts aren't monitored and have passwords that may not have been changed for a long time. So, if you want to take action on such inactive accounts, you will first need to have a list of all such inactive accounts in your AD network. This can be achieved using a simple PowerShell script.
The following script, when run against an AD domain, will generate a report of all the inactive accounts in the network.
- PS C:\> Import-module activedirectory
- $DaysInactive = 30
- $time = (Get-Date).Adddays(-($DaysInactive))
- Get-ADUser -Filter {LastLogonTimeStamp -gt $time -and enabled -eq $true}
- -Properties LastLogonTimeStamp | select-object Name,@{Name="Stamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy-MM-dd_hh:mm:ss')}} | export-csv C:\Scripts\activeusers.csv -notypeinformation