Stale accounts are a primary vector for lateral movement in a compromised network. This script automates the “Sanitization” phase of identity management by identifying and disabling dormant accounts.

1. The Logic Flow

The script follows a safe-failure logic to ensure no critical service accounts are accidentally disabled:

  1. Targeting: Narrowly scopes the search to specific User OUs.
  2. Evaluation: Filters for LastLogonDate older than 90 days.
  3. Action: Disables the account and logs the event for auditing.

2. The Implementation

# Configuration
$DaysInactive = -90
$TargetDate = (Get-Date).AddDays($DaysInactive)
$LogPath = "C:\Logs\AD_Cleanup_$(Get-Date -Format 'yyyyMMdd').log"

# Fetch and Process
Get-ADUser -Filter 'LastLogonDate -lt $TargetDate -and Enabled -eq $true' -Properties LastLogonDate | 
    ForEach-Object {
        $User = $_.SamAccountName
        try {
            # Use -WhatIf for safety during testing
            Disable-ADAccount -Identity $_.DistinguishedName -ErrorAction Stop
            Add-Content -Path $LogPath -Value "SUCCESS: Disabled $User (Last Login: $($_.LastLogonDate))"
        } catch {
            Add-Content -Path $LogPath -Value "ERROR: Failed to disable $User. Check permissions."
        }
    }