MSP·OUTPOST
Menu
PowerShell · Active Directory

Disable stale Active Directory accounts

Run on a domain controller or a machine with RSAT. It finds enabled users whose LastLogonDate is older than the threshold, disables them, stamps the description with the date, and moves them to a holding OU. Always review the -WhatIf output before running for real.

Script

Code

Import-Module ActiveDirectory
$DaysInactive = 90
$DisabledOU = "OU=Disabled Users,DC=example,DC=com"

Search-ADAccount -AccountInactive -TimeSpan ([TimeSpan]::FromDays($DaysInactive)) -UsersOnly |
  Where-Object { $_.Enabled -eq $true } |
  ForEach-Object {
    Disable-ADAccount -Identity $_.DistinguishedName
    Set-ADUser -Identity $_.DistinguishedName `
      -Description ("Disabled by automation {0:yyyy-MM-dd}" -f (Get-Date))
    Move-ADObject -Identity $_.DistinguishedName -TargetPath $DisabledOU
    Write-Output "Disabled: $($_.SamAccountName)"
  }
Usage

How to use this script

Run on a domain controller or a machine with RSAT. It finds enabled users whose LastLogonDate is older than the threshold, disables them, stamps the description with the date, and moves them to a holding OU. Always review the -WhatIf output before running for real.

Review the script and test in a non-production environment before running at scale.

Tags
active-directoryoffboardingcleanup