Users who should have been removed from active directory but weren't is one of the most common issues that comes up in a network assessment for new clients. Often times companies simply forget to notify their IT provider that someone has been let go, or the ticket kept getting pushed off until it was forgotten about.

Luckily, we have PowerShell to auomate the process of finding all of the accounts that haven't logged in within a certain number of days. To start, we need to define how long we want to check against and get a list of all of the enabled ActiveDirectory accounts:

# Any user who hasn't logged in within this date
# will be added to our list
$InactiveDate = (Get-Date).AddDays(-30)

# Get all active users in ActiveDirectory
$Users = Get-ADUser -Filter 'Enabled -eq $True' -Properties LastLogonDate

# Create a container Array to hold the list of
# inactive users for later
$InactiveUsers = @()

There's a ton of properties available from the users, but we only care about the base set (DN, Display Name, SID, etc.) and the LastLogonDate property.

Now, it's just a matter of looping through the array to get the inactive users:

# Loop through all of the users
$Users | ForEach-Object {
	# Check if the LastLogonDate is less than or equal to the InactiveDate (30 days ago)
	if ($_.LastLogonDate -le $InactiveDate) {
		# Add the user to our list if it hasn't logged in
		$InactiveUsers += $_
	}
}

Now the $InactiveUsers variable holds our list of users who haven't logged in within 30 days.


Here is the full script put together including outputting the list to CSV:

###
# Author: Dave Long <dlong@cagedata.com>
# Created Date: 2019-08-01
# Description: Gets a list of all inactive users and optionally disables them
###

function Get-InactiveUsers($Disable=$False) {
    # Any user who hasn't logged in within this date
    # will be added to our list
    $InactiveDate = (Get-Date).AddDays(-30)

    # Get all active users in ActiveDirectory
    $Users = Get-ADUser -Filter 'Enabled -eq $True' -Properties LastLogonDate

    # Create a container Array to hold the list of
    # inactive users for later
    $InactiveUsers = @()

    # Loop through all of the users
    $Users | ForEach-Object {
	    # Check if the LastLogonDate is less than or equal to the InactiveDate (30 days ago)
	    if ($_.LastLogonDate -le $InactiveDate) {
		    # Add the user to our list if it hasn't logged in
		    $InactiveUsers += $_
            if ($Disable) { Set-ADUser $User -Enabled $False }
        }
    }
    return $InactiveUsers
}

Get-InactiveUsers | Export-CSV -Path C:\Inactive-Users.csv

Get this script and others that I've written on GitHub