Friday, June 27, 2008

E-mail when passwords are going to expire

$DateTime1 = Get-Date -format "MM-dd-yyyy"
$DateTime = Get-Date -format "yyyy-MM-dd HH.mm.ss"
$PasswordExpires7Days = "PasswordExpires7Days"+"$DateTime"+".txt"

## get the Domain Policy
## for the maximum password age
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()

## get the account policy
$search = [System.DirectoryServices.DirectorySearcher]$root
$search.Filter = "(objectclass=domainDNS)"
$result = $search.FindOne()

## maximum password age
$t = New-Object System.TimeSpan([System.Math]::ABS($result.properties["maxpwdage"][0]))

##get -PasswordNeverExpires
##$p = Get-QADuser -PasswordNeverExpires $false

## want all accounts where password will expire in next 7 days
## ie password was set (max password age) - 7 days ago
$d = ($t.Days)* -1 ## max password age days ago
$d1 = $d +7 ## 7 days on from max password age
Start-Transcript -path "c:\PowerShell\$PasswordExpires7Days"
Get-QADUser -IncludeAllProperties | Where {($_.PwdLastSet -gt (Get-Date).AddDays($d)) -and ($_.PwdLastSet -lt (Get-Date).AddDays($d1) -and ($_.PasswordNeverExpires -eq $false))} | Sort-Object -Property pwdLastSet -Descending | format-table Name,PwdLastSet
stop-transcript


$EmailBody1= get-content "c:\PowerShell\$PasswordExpires7Days"
$EmailBody= "c:\PowerShell\$PasswordExpires7Days"

# when done, send us an email with the log text


$SmtpClient = new-object system.net.mail.smtpClient
$MailMessage = New-Object system.net.mail.mailmessage
$att = new-object system.Net.Mail.Attachment($EmailBody)
$SmtpClient.Host = "sch-ca01.yourdomain.com"
$mailmessage.from = ("someone@yourdomain.com")
$mailmessage.To.add("someone@yourdomain.com")
#$mailmessage.To.add("someone@yourdomain.com,someoneelse@yourdomain.com,someoneelse@yourdomain.com")
$mailmessage.Subject = "Passwords that are going to expire " + "$DateTime1"
$mailmessage.Body = $EmailBody1
$mailmessage.Headers.Add("message-id", "<3bd50098e401463aa228377848493927-1>")
$mailmessage.Attachments.Add($att)
$smtpclient.Send($mailmessage)

No comments: