Active Directory Stale Account Management

Recently had a client that would like to automate stale account management without investing in a full blown identity management solution. Here is the script I came up with.

  • Gets users that have not logged in 90 days
  • Counts and sends email to administrator of accounts that where disabled
  • Sets user description with date of disabled as well as that it was disabled by the script
  • Finally it disables the accounts

There are more elegant solutions and scripts feel free to improve as you wish.

function sendMail{

#Set Date
$90Days = (get-date).adddays(-90)

#get Users before or equal to that date & enabled
$todisable = Get-ADUser -SearchBase "OU=Users,DC=contoso,DC=com" -filter {(lastlogondate -le $90days) -AND (enabled -eq $True)} -Properties lastlogondate

#count the users
$count = $todisable.count

#edit the description
$todisable | Set-ADUser -replace @{description="$($_.description) Disabled By Stale User Script $(get-date -format d) "}

#disable the accounts
$todisable | Disable-ADAccount

#SMTP server name
$smtpServer = ""

#Creating a Mail object
$msg = new-object Net.Mail.MailMessage

#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

#Email structure
$msg.From = ""
$msg.ReplyTo = ""
$msg.subject = "Stale User Script has Disabled $count Accounts"
$msg.IsBodyHtml = $True
$msg.body = $todisable | Select-object name,DistinguishedName,LastLogonDate | ConvertTo-Html -Head $style | out-string
#Sending email


I used some information from here for the mail information.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s