Dave Herrell - Blog - IT Toolbox - PowerShell Banner

PowerShell Basics: Create List of Disabled Users

Depending on the company, you may need to do a quarterly audits to verify off-boards or maybe your policy states disabled or off-board accounts need to be removed every so often.  PowerShell is handy for that. 

The script below will scan your entire AD enviroment and save a CSV with the usersname, and when changed date.  Now the whenChanged date maybe different if someone has updated the AD account.  Since Microsoft doesn’t keep a specific attribute record for disable date/time (as they should) this is the best one to use.  

Make sure you update the export path with your desired location, and run as administrator. 

				
					# Import Active Directory module
Import-Module ActiveDirectory

# Function to get the account disable date from the user's lastLogoff attribute
function Get-AccountDisableDate {
    param (
        [Parameter(Mandatory=$true)]
        [string]$DistinguishedName
    )
    $accountExpires = (Get-ADUser -Identity $DistinguishedName -Properties whenChanged).whenChanged
    return $accountExpires
}

# Get all disabled user accounts
$disabledUsers = Get-ADUser -Filter {Enabled -eq $false} -Property DisplayName, sAMAccountName, UserPrincipalName, whenChanged

# Create a custom object to hold the user details and disable date
$results = foreach ($user in $disabledUsers) {
    [PSCustomObject]@{
        DisplayName      = $user.DisplayName
        sAMAccountName   = $user.sAMAccountName
        UserPrincipalName = $user.UserPrincipalName
        DisabledDate     = $user.whenChanged
    }
}

# Display the list of disabled users with disable dates
$results | Format-Table -AutoSize

# Export the list to a CSV file
$results | Export-csv -path C:\Users\dave\Desktop\DisabledUsers.csv -NoTypeInformation

Write-Output "The list of disabled user accounts with disable dates has been retrieved and saved to DisabledUsersWithDate.csv."

				
			

This will export the CSV to your destination and print the output on the screen simliar to this: 

I’ve found this handy for various quarterly audits.  

Hope you find this helpful!