Powershell - email Office 365 password expiration reminders


Great script that I found for password reminders



# RUN THIS COMMAND ON THE MACHINE THAT WILL RUN THE SCRIPT TO STORE THE PASSWORD:
# read-host -prompt "Enter password to be encrypted in mypassword.txt " -assecurestring | convertfrom-securestring | out-file C:\somefolder\secure_o365.txt

$pass = cat C:\somefolder\secure_o365.txt | convertto-securestring
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist "admin@your_domain.org",$pass
Import-Module MsOnline
Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
$exchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid/" -Credential $credential -Authentication "Basic" -AllowRedirection
Import-PSSession $exchangeSession -DisableNameChecking
Connect-MsolService -Credential $credential
# initial variables
$today = get-date
$users = Get-MsolUser | Where-Object {$_.isLicensed -eq $true -and $_.PasswordNeverExpires -eq $false }
$email_smtp = "192.168.123.4"
$email_from = "it@your_domain.org"
$log = "List of people emailed:`n`r`n`r"
$log_len = $log.length
$log_subject = "emailed office365 passwords expiring reminders"
$email_log_to = "it@your_domain.org"


#process users
foreach ($user in $users)
{
 # get when password expires_in_days
 $expires_date = $user.LastPasswordChangeTimestamp.AddDays(90)
 $tspan=New-TimeSpan $today $expires_date 
 $expires_in_days = $tspan.days
 # get their  email address
 $email_to = $user.SignInName
 # build message text
 if ($expires_in_days -eq 1 )
 {
  $day_text = "day"
 } else {
  $day_text = "days" 
 }
 # process expiring passwords
 if ($expires_in_days -le 10 -and $expires_in_days -ge 0 )
 {
  $email_subject = "NONE"
  # build message text
  if ($expires_in_days -eq 10 -or ( $expires_in_days -le 5 -and $expires_in_days -gt 0 ))
  {
   $email_subject = "your email password expires in " + $expires_in_days + " " + $day_text
  } elseif ($expires_in_days -eq 0 ) {
   $email_subject = "your email password expires today!"
  }
  # send email if needed
  if ($email_subject -ne "NONE")
  {
   $email_body = "Your email password will expire: " + $expires_date + ".`n`r`n`rPlease change your Office365 password by visiting http://portal.office.com.`n`r`n`rSee https://your_domain.sharepoint.com/FAQ/Changing%20Your%20Outlook%20Passwords%20in%20Office365.docx for instructions.`n`r`n`r"
   # build log
   $log = $log + $email_to + " " + $expires_in_days + "`n`r"
   Send-MailMessage -To $email_to -Subject $email_subject -Body $email_body -SmtpServer $email_smtp -From $email_from
  }
 }
}

# send log
if ($log.length -gt $log_len)
{
 Send-MailMessage -To $email_log_to -Subject $log_subject -Body $log -SmtpServer $email_smtp -From $email_from
}