UPDATED: Jan 16 2024
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.
This script is pretty self explanatory and easy to modify. So, for instance, if you want only those that have not been touched, in 2 years change .ADDYEARS(-2).
Note that this script will also output any user account that has never been logged into, including brand new ones.
$inactiveUsers = Get-ADUser -Filter {Enabled -eq $True} -Properties SamAccountName, whenCreated, LastLogonDate | Where-Object { $_.LastLogonDate -lt (Get-Date).AddYears(-1) }
$output = $inactiveUsers | Select-Object SamAccountName, whenCreated, LastLogonDate | ConvertTo-Csv -NoTypeInformation
Set-Content -Path "C:\temp\DeadUsers.csv" -Value $output
Write-Host "Results have been saved to C:\temp\DeadUsers.csv"
Note that the hardest part of using this script is figuring out what your fully qualified OU name is. Fortunately there is a VERY easy way to figure that out. If you need to know the fully distinguished name of an OU, click HERE for the instructions and screenshot.
# 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.
This website uses cookies.
View Comments