Secure User Account Audit Script

In this post, we will share a useful PowerShell script that audits user accounts for security compliance. This script will help system administrators identify inactive user accounts and report them for further action. This is an important step in maintaining a secure environment by ensuring that only active accounts have access to critical resources.
Step 1: Define Variables
First, we will define some variables to store the necessary data such as the log file path and the threshold for inactivity.

$logFile = "C:\UserAccountAudit.log"
$inactiveDaysThreshold = 90

Step 2: Get Current Date
Next, we will get the current date to compare against user account last logon dates.

$currentDate = Get-Date

Step 3: Retrieve User Accounts
We will retrieve all user accounts from Active Directory along with their last logon date.

$users = Get-ADUser -Filter * -Property LastLogonDate

Step 4: Filter Inactive Users
Filter the user accounts to find those that haven’t logged on in the past specified number of days.

$inactiveUsers = $users | Where-Object {
    ($currentDate - $_.LastLogonDate).Days -gt $inactiveDaysThreshold
}

Step 5: Log Inactive Users
Finally, we will log the inactive user accounts to the specified log file.

if ($inactiveUsers) {
    $inactiveUsers | ForEach-Object {
        Add-Content -Path $logFile -Value "$($_.Name) is inactive since $($_.LastLogonDate)"
    }
} else {
    Add-Content -Path $logFile -Value "No inactive accounts found."
}

Step 6: Output Result
Output the results to the console for immediate feedback.

Get-Content -Path $logFile | Write-Host

This script provides a comprehensive overview of user account activity, allowing you to proactively manage and secure user access within your organization.