Automate User Account Auditing in Active Directory with PowerShell

In this post, we will present a PowerShell script to automate user account auditing in Active Directory. Regularly auditing user accounts is essential for maintaining security and compliance within an organization. This script retrieves important details for all user accounts, including last logon times and account status, helping administrators identify inactive or potentially compromised accounts quickly.
Here is the PowerShell script for auditing user accounts in Active Directory:

# Import the Active Directory module
Import-Module ActiveDirectory
# Retrieve all user accounts
$users = Get-ADUser -Filter * -Property DisplayName, LastLogonDate, Enabled
# Create a report array
$auditReport = @()
foreach ($user in $users) {
    $auditReport += [PSCustomObject]@{
        DisplayName   = $user.DisplayName
        LastLogonDate = $user.LastLogonDate
        AccountStatus = if ($user.Enabled) { "Enabled" } else { "Disabled" }
    }
}
# Output the audit report
$auditReport | Sort-Object LastLogonDate | Format-Table -AutoSize
Write-Host "User account auditing completed successfully."