Powershell script + SMTP email

Kevin Savard Vertisoft 86 Reputation points
2023-01-20T14:10:44+00:00

Hello,

I have the following script edited by my co-worker (it's our IP) with my own 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!


By the way - = # I don't want it to take half of the page because it gives my post big characters.

# 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" # Test mod on disable for the user to receive an email.

$testRecipient = "hidden@random.com"

$SendToSupervisor = "Enabled" # Set to Enabled Pour que le superviseur reçoit 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.
974 questions
Exchange Server Management
Exchange Server Management
Exchange Server: A family of Microsoft client/server messaging and collaboration software.Management: The act or process of organizing, handling, directing or controlling something.
7,237 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,281 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
1,864 questions
{count} votes

1 additional answer

Sort by: Most helpful
  1. Kevin Savard Vertisoft 86 Reputation points
    2023-01-20T15:55:49.15+00:00

    I figured my problem. A line were overwriting another one in the screen of my powershell. Thanks for the help.

    1 person found this answer helpful.
    0 comments No comments