Thursday 12 March 2020

Password Expire Email Notification

The below script would help us to send an email notification, when user password expires on specific group members. 




Remove-Item C:\temp\Password.html -Force

$Domainname = (Get-ADDomain).Name

$PasswordPolicy = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge.days

$Today = (Get-Date).AddDays($PasswordPolicy)

$Users = Get-ADGroupMember -Identity "GroupName" | Get-ADUser | Where-Object {$_.Enabled -eq $true} |Select-Object -ExpandProperty SamAccountName

$CustomDay = 10

foreach ($User in $users) {

   $Pass = ((Get-ADUser -Identity $User -Properties * | Select-Object -ExpandProperty passwordlastset) - $Today).Days

    If ($pass -ge $CustomDay) {
   
        Get-Aduser -Identity $User -Properties * | Select-Object SamAccountName,passwordlastset,@{Name="PasswordExpiredON";e={$Pass}} | ConvertTo-Html | Out-File -Append "C:\Temp\Password.html"
   
    } elseif ($pass -le $CustomDay){

        Get-Aduser -Identity $User -Properties * | Select-Object SamAccountName,passwordlastset,@{Name="PasswordAlredyExpired";e={$Pass}} | ConvertTo-Html | Out-File -Append "C:\Temp\Password.html"
   
       
    }
    else {
        Out-File "All User Look Good" | ConvertTo-Html | Out-File -Append "C:\Temp\Password.html"

    }
    }


$Result = Get-Content C:\temp\password.html -Raw

# Creating Email Variable

$subject = "Password Expire Notification for the Domain" + $domainname
$priority = "Normal"
$smtpServer = "mail.test.com"
$emailFrom = "email@test.com"
$emailTo = "email@test.com"

# Sedning Report

Send-MailMessage -To $emailTo -Subject $subject -Body $Result -BodyAsHtml -SmtpServer $smtpServer -From $emailFrom -Priority $priority


No comments:

Post a Comment