At Up & Running Technologies were pretty good about disabling and then deleting old accounts but an awful lot of administrators just let the account sit. However, eventually there comes a time when someone starts screaming about how many accounts they have and how much that increases the company’s attack surface. At that point it’s time for you to figure out which accounts are dead and deal with them.

The simple script below will export a list of users that have either never logged in or not logged in within the last one year. To make this more meaningful to others in the organization we’ve also included the whenCreated field so you can easily explain to others when an account was created and when it was last logged into, if ever.

# Import the Active Directory module if not already loaded
if (-not (Get-Module -Name ActiveDirectory -ErrorAction SilentlyContinue)) {
    Import-Module ActiveDirectory

# Define the date one year ago from today
$oneYearAgo = (Get-Date).AddYears(-1)

# Specify the OU path for the "USERS" OU
$usersOU = "OU=User Accounts,DC=YoutDomain,DC=LOCAL"  # Replace with your domain information

# Search for users in the specified OU who haven't logged in within the last year
$inactiveUsers = Get-ADUser -Filter {
    (LastLogonDate -lt $oneYearAgo) -or (LastLogonDate -notlike "*")
} -SearchBase $usersOU -Properties LastLogonDate, whenCreated

# Display the list of inactive users
$inactiveUsers | Select-Object Name, SamAccountName, whenCreated, LastLogonDate | Format-Table -AutoSize > C:\temp\DeadUsers.txt  # Replace with the path and file name you want

The commands themselves are pretty clear but we have included some remarks to remind you to change the domain name, for instance to whatever your domain actually is.

1 Comment

SOLVED: How To Determine The Last Time A User Logged On, Logged Off & Was Created in Active Directory – Up & Running Technologies, Tech How To's · September 23, 2023 at 11:02 am

[…] an article we published yesterday, we provided a simple PowerShell script to export a list of all of your stale Active Directory user accounts to a simple text file with nice columns that you could manipulate in […]

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *