Month: January 2015

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 = "exch.contoso.com"

#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 = "script@contoso.com"
$msg.ReplyTo = "script@contoso.com"
$msg.To.Add("brent@contoso.com")
$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
$smtp.Send($msg)

}
sendmail

I used some information from here http://blogs.msdn.com/b/rkramesh/archive/2012/03/16/sending-email-using-powershell-script.aspx for the mail information.