Clean up Service accounts in AD

I have five domain controller that i need to powershell against, essentially i need to clean up service accounts (user accounts) to determine what can be safely deleted, and query the following into a CSV:

CN,samaccountname,displayName,lastLogon,lastLogonTimestamp,mail or target address

My service accounts live in the following OU’s:

OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=POC,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=Sharepoint Dev,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=Sharepoint Prd,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=EPC Sandbox,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=IS OnCall,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=EPC Dev,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=EPC Prd,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=MobileIron Accounts,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=DEV,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com
OU=Azure Service Accounts,OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com

So far i have this but it isn’t reporting on “lastlogon”, or “displayname”. Really need some help please!
Get-ADUser -Filter * -SearchBase “OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com” -ResultPageSize 0 -Prop CN,samaccountname,displayName,lastLogon,lastLogonTimestamp | Export-CSV C:\SSGServiceAccounts\Users.csv -NoType

I’m assuming you’re getting a random value that is not in the format you are looking for?


I am getting a radom value due to logons hitting anyone of the five domain controllers. It would be nice to just export users in an OU and filter on samaccountname,displayName,lastLogon,lastLogonTimestamp, and export to a readable CSV is all I need.

If you modify the code you have above with the information in the link that I sent, does it not give you that information? When you run that, what is the output you get vs the expected output?

Why are you using -resultspagesize ?

Try this one

Get-ADUser -Filter * -SearchBase "OU=Service Accounts,OU=SSG,DC=ssg,DC=domainname,DC=com" -Properties * | Format-Table CN,samaccountname,displayName,lastLogon,lastLogonTimestamp