Powershell script + SMTP server does not work properly

Kevin Savard Vertisoft 86 Reputation points
2023-01-20T13:47:23.19+00:00

WARNING! There was an error parsing the document

Hello,

I have the following script that I found online with my personal modification. I have basic skills in powershell so I'm not a master. The goal is to send an email to the user as soon as he hits a 14-day countdown until having his password expired. It will give them enough time to reset it before the radius VPN stop working. The rest of the script is working properly. Like the part that sends an email to the supervisor. I would need your help to fix the part that is supposed to send the email to the user. I hid personals information for security purposes. Some parts are in French since it’s my first language.

Thanks for your help!

Configuration des variables

$smtpServer= "hidden@random.com"

$expireindays = 14

$from = "hidden@random.com"

$logging = "Enabled" # Set to Disabled to Disable Logging

$logFile = "C:\Users\admin\Desktop\passwordexpirationlog.csv" # EX: c:\Expiration.csv

$testing = "Disabled" # Mode de test Set to Disabled pour que l'usager reçoive un courriel d'avis

$testRecipient = "hidden@random.com"

$SendToSupervisor = "Enabled" # Set to Enabled Pour que le superviseur reçoive le fichier de logto Disable Logging

$Supervisor = "hidden@random.com" # Le superviseur recevra le fichier de log

$Expiration = "Yes"

###########################################################

########################################################

Vérification de la journalisation

if (($logging) -eq "Enabled")

{

Test Log File Path

$logfilePath = (Test-Path $logFile)

if (($logFilePath) -ne "True" -or $SendToSupervisor -eq "Enabled" )

{

if (Test-Path $logFile -PathType leaf)

{

Remove-Item $logFile

}

Create CSV File and Headers

New-Item $logfile -ItemType File

Add-Content $logfile "Date,Name,EmailAddress,DaystoExpire,ExpiresOn,Notified"

}

} # End Logging Check

Paramètre du systeme

$textEncoding = [System.Text.Encoding]::UTF8

$date = Get-Date -format ddMMyyyy

Fin de vérification des paramètres du systeme

Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired

Import-Module ActiveDirectory

$users = get-aduser -filter * -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress | where {$.Enabled -eq "True"} | where {$.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false }

$DefaultmaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge

Process Each User for Password Expiry

foreach ($user in $users)

{

$Name = $user.Name

$emailaddress = $user.emailaddress

$passwordSetDate = $user.PasswordLastSet

$PasswordPol = (Get-AduserResultantPasswordPolicy $user)

$sent = "" # Reset Sent Flag

Check for Fine Grained Password

if (($PasswordPol) -ne $null)

{

$maxPasswordAge = ($PasswordPol).MaxPasswordAge

}

else

{

No FGP set to Domain Default

$maxPasswordAge = $DefaultmaxPasswordAge

}

$expireson = $passwordsetdate + $maxPasswordAge

$today = (get-date)

$daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days

Set Greeting based on Number of Days to Expiry.

Check Number of Days to Expiry

$messageDays = $daystoexpire

if (($messageDays) -gt "1")

{

$messageDays = "in " + "$daystoexpire" + " days."

$messageJours = "dans " + "$daystoexpire" + " jours."

}

else

{

$messageDays = "today."

$messageJours = "Aujourd'hui"

}

Email Subject Set Here

$subject="Votre mot de passe va expirer $messageJours | Your password will expire

$messageDays"

Email Body Set Here, Note You can use HTML, including Images.

$body ="

À l'attention de $name,

<p> Votre mot de passe réseau va expirer $messageJours<br>

Pour changer votre mot de passe sur un ordinateur quand vous êtes au bureau, appuyez sur

CTRL+ALT+Delete et sélectionnez « changer de mot de passe ». <br>

Pour changer votre mot de passe sur un ordinateur quand vous êtes à la maison, votre VPN doitêtre

actif, appuyez sur CTRL+ALT+Delete et sélectionnez « changer de mot de passe ». Assurez-vous d'être connecter au VPN pour le faire, sauf si vous êtes au bureau. <br>

<p>Merci, <br>

</P>

Dear $name,

<p> Your Password will expire $messageDays<br>

To change your password on a computer when you are at the office, press CTRL+ALT+Delete

and choose « Change Password ». <br>

To change your password on a computer when you are at home, your VPN need to be active ,

press CTRL+ALT+Delete and choose « Change Password ». Make sure you are connected with the VPN unless you are at the office. <br>

<p>Thanks, <br>

</P>"

If Testing Is Enabled - Email Administrator

if (($testing) -eq "Enabled")

{

$emailaddress = $testRecipient

} # End Testing

If a user has no email address listed

if (($emailaddress) -eq $null)

{

$emailaddress = $testRecipient

}# End No Valid Email

Send Email Message

if (($daystoexpire -ge "0") -and ($daystoexpire -lt $expireindays))

{

$sent = "Yes"

$Expiration = "Yes"

If Logging is Enabled Log Details

if (($logging) -eq "Enabled")

{

Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$sent"

}

Send Email Message

Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $textEncoding

} # End Send Message

else # Log Non Expiring Password

{

$sent = "No"

If Logging is Enabled Log Details

if (($logging) -eq "Enabled")

{

Add-Content $logfile "$date,$Name,$emailaddress,$daystoExpire,$expireson,$sent"

}

}

} # End User Processing

Si $Logging et $SendToSupervisor sont a "Enabled le fichier de log est envoyer au superviseur seulement si un mot de passe envoie d'expiration est trouvé

if (($logging) -eq "Enabled" -and $SendToSupervisor -eq "Enabled" -and $Expiration -eq "Yes" )

{

$Subject = "Rapport d'expiration des mots de passe des usagers"

$Body = "Bonjour, Voici le rapport d'expiration des mots de passe. Merci!"

#write-host $Subjet

#write-host $Body

#write-host $Supervisor

#write-host $logFile

#write-host $smtpServer

#Pause

Send-MailMessage -to $Supervisor -subject $Subject -body $Body -smtpserver $SMTPServer -from $From -Attachments $logFile

#write-host "Courriel envoyé"

}

End

Exchange Server
Exchange Server
A family of Microsoft client/server messaging and collaboration software.
1,337 questions
Windows Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
13,218 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,550 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,588 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 44,386 Reputation points
    2023-01-23T16:09:29.6566667+00:00
    Hello there,
    
    Instead of troubleshooitng your code can you try the below script and see if that helps.
    
    Use the following PowerShell script to check user password expiration dates and send an expiry notification email seven days in advance:
    
    #Import AD Module
     Import-Module ActiveDirectory
     
    #Create warning dates for future password expiration
    $SevenDayWarnDate = (get-date).adddays(7).ToLongDateString()
    
    #Email Variables
    $MailSender = " Password AutoBot <emailaddress@somecompany.com>"
    $Subject = 'FYI - Your account password will expire soon'
    $EmailStub1 = 'I am a bot and performed this action automatically. I am here to inform you that the password for'
    $EmailStub2 = 'will expire in'
    $EmailStub3 = 'days on'
    $EmailStub4 = '. Please contact the help desk if you need assistance changing your password. DO NOT REPLY TO THIS EMAIL.'
    $SMTPServer = 'smtp.somecompany.com'
     
    #Find accounts that are enabled and have expiring passwords
    $users = Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq $False -and PasswordLastSet -gt 0 } `
     -Properties "Name", "EmailAddress", "msDS-UserPasswordExpiryTimeComputed" | Select-Object -Property "Name", "EmailAddress", `
     @{Name = "PasswordExpiry"; Expression = {[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed").tolongdatestring() }}
     
    #check password expiration date and send email on match
    foreach ($user in $users) {
         if ($user.PasswordExpiry -eq $SevenDayWarnDate) {
             $days = 7
             $EmailBody = $EmailStub1, $user.name, $EmailStub2, $days, $EmailStub3, $SevenDayWarnDate, $EmailStub4 -join ' '
     
             Send-MailMessage -To $user.EmailAddress -From $MailSender -SmtpServer $SMTPServer -Subject $Subject -Body $EmailBody
         }
        else {}
     }
    
    
    Hope this resolves your Query !!
    
    --If the reply is helpful, please Upvote and Accept it as an answer–
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.