Active Directory Account Expiration Notification to Managers
Hello script gurus - I wanted to send an automatic email notification to managers pertaining to their contractors that has an end date on their AD accounts. The script that I found had most of the features I’m looking for. However need assistance on how to add the following into the script.
- Add additional message into the body of the email.
Thank you for your time and appreciate any assistance!
Cheers.
Get-ADUser -Filter * -Properties directReports,EmailAddress | ForEach {
$body = @()
If ($_.directReports) {
$managerEmailAddress = $_.EmailAddress
$_.directReports | ForEach {
$userDetails = Get-ADUser $_ -Properties AccountExpirationDate
If ( $userDetails.AccountExpirationDate ) {
If ( $userDetails.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {
$sendEmail = $true
$props = [ordered]@{
Username=$userDetails.SamAccountName
‘Account Expiration Date’=$userDetails.AccountExpirationDate
}
$body += New-Object PsObject -Property $props
}
}
}
}
If ($sendEmail) {
$body = $body | Out-String
Send-MailMessage -From ‘email@domain.com’ -To $managerEmailAddress -Subject ‘Account Expiration Report’ -Body $body -SmtpServer ‘mail.domain.com’
}
$sendEmail = $false
}
Generic check for users with no manager
$bodyNM = @()
Get-ADUser -Filter * -Properties AccountExpirationDate,Manager | ForEach {
If ( !$_.Manager ) {
If ( $_.AccountExpirationDate) {
If ($_.AccountExpirationDate -lt (Get-Date).AddDays(30) ) {
$sendEmailNM = $true
$propsNM = [ordered]@{
Username=$.SamAccountName
‘Account Expiration Date’=$.AccountExpirationDate
}
$bodyNM += New-Object PsObject -Property $propsNM
}
}
}
}
If ($sendEmailNM) {
$bodyNM = $bodyNM | Out-String
Send-MailMessage -From ‘email@domain.com’ -To ‘helpdesk@domain.com’ -Subject ‘Account Expiration Report’ -Body $bodyNM -SmtpServer ‘mail.domain.com’
}