Find Expired Accounts in Active Directory using Powershell
We all know, people join organizations and leave organizations at regular intervals. And we as System Administrators have to create and manage their user accounts in Active Directory.
As a best practice, we all set an expiration date to the user account that is created. But do we delete those accounts if they are no longer in use? Its hard to tell based on the company’s policies and procedures. Therefore, today we will see how to find the expired accounts in the domain and you can do the same in your organization.
We will be using Search-ADAccount cmdlet to perform this activity. You can do Get-Help Search-ADAccount to get more information and use cases of the cmdlet.
Now type the below on your screen.
Search-ADAccount -AccountExpired | select Name, samAccountName, ObjectClass, AccountExpirationDate, lastLogonDate | Export-Csv c:\ExpiredAccounts.csv
Let us see what we did here.
First we used the Search-ADAccount cmdlet with one of its parameters AccountExpired which will search for all the expired accounts in the domain.
Next we are selecting Name, samAccountName and the ObjectClass of the account, the Account Expiration Date and the Last Logon time. The ObjectClass can be a user or a computer.
After which we are exporting the result to a csv file with the help of the Export-Csv cmdlet.
If you want to select only the User Accounts then we can select the parameter UsersOnly along with the Search-ADAccount cmdlet to find the same.
Similarly we can use ComputersOnly parameter to see for computer accounts.
If you are using User Accounts only then you can find out what are the properties avilable to export with the help of Get-Member cmdlet. See below for example.
I hope this was informative and thank you for reading!