Password Expiry Email Notification

This script will email a user in the event that their password is due to expire in X number of days. I have now moved it to GitHub - https://github.com/titlerequired/public

 
 
 
 
 
4.6 Star
(153)
89,027 times
Add to favorites
Active Directory
7/2/2020
E-mail Twitter del.icio.us Digg Facebook
  • Anonymous Email send
    4 Posts | Last post June 27, 2018
    • We have this setup to Run from a Task Schedule.  The user account used to run the task schedule has a mailbox and we use that same account as the From account, however when trying to run it we get the following error: Mailbox unavailable. The server response was: 5.7.1 Client does not have permissions to send as this
      
      This is because its using an authenticated account so my question is. Is there anyway to run this whereas it sends the notification emails to the users using anonymous SMTP instead and if so what changes would i need to make to the Powershell code
    • Allowing anonymous SMTP is a setting on the server side,  or you can try to use SMTP Authentication.
      https://www.youtube.com/watch?v=_-JHzG_LNvw
    • Sorry Robert I only asked that as it was something I may look to try in the future. My current issue is that I cant run the Task schedule anymore through my standard Domain User account. I know it only works with an account that has permission to relay email hence why I previously used this and it used to work fine however I recently moved the TS and PS1 Script to a new server and ever since when I used the same credentials i get the following error when trying to set the same user account in the Task Scheduler:  
      
      This task requires that the user account specified has log on as batch job rights.  I cannot change this as the option in secpol is greyed out due to it being controlled by the Domain Controllers GPO
      
      Do you know why this is suddenly asking for this as this wasn't the case on the previous server I used.  Appreciate your help here thanks
    • Make the user a member of the backup operators group on the machine the script runs on.
  • Translation
    6 Posts | Last post June 27, 2018
    • Hi Robert,
      I would like to know if is possible to translate $expireInDays for a different language? In my case, portuguese.
      
      Thanks for you attention.
    • What format should it be in for Portuguese?
    • Instead of "expire in xx days" in portuguese should be "expirar em xx dias".
      
      Many thanks.
    • Oh, well yes you can change the $body text to say whatever you want.
    • That´s the thing, I can´t coz the message is been parsed by $messageDays which autocomplete to xx days!
      
      Both subject and also the body tag are using same parameters.
      
      Or I´m talking s****?
      
      Thanks.
    • Have a look at line 168 - $subject = "Your password..." you can change that to whatever you like.
      
      and Line 166 -$messageDays = "" you can change to whatever you want.
  • Hi, is this script can be run on windows 10? or windows server only? Thank you
    2 Posts | Last post June 22, 2018
    • can we run this scripts in windows 10? or windows server only? Our password will expire in 90 days and we want the users to be notified via email. Thank you so much.
    • It is for Active Directory, so if you have an AD Domain you can use it, and run the script from where ever you want.
  • Inlineattachments
    5 Posts | Last post June 22, 2018
    • Robert,
       I got inlineattachments to work. Displays correctly in outlook. The image appears at the bottom of the e-mail from an iphone. Here is what Im doing. This is been shortened to fit here. Ideas ?
          $attachment = Get-Item C:\chgpwsd\change_password_ico.png
          $textEncoding = [System.Text.Encoding]::UTF8
          # Set Greeting Message
          $messageDays = 5
          # Subject Setting
          $subject="Your password will expire soon"
          # Email Body Set Here, Note You can use HTML, including Images.
          $body ="
          <font face=""verdana"">
          
          <p> Your Password will expire in  <b>$messageDays days</b>. <img src=""{0}""width=""30"" height=""40"" /> <br>
          <p>If you are traveling, you can change your password from your mobile device. <br>
          <a href=""https://somwhere.rainbow.com/owa/?ae=Options&t=ChangePassword"">Click here</a>, login to whatever follow the prompts.  
      
          <a href=""mailto:somewhere@rainbow.com?Subject=Password Expiry Assistance"">somewhere@rainbow.com</a> | <a href=""tel:0000000"">Phone:0000000</a>
          </font>" -f ($attachment.Name)
         
      Send-Mailmessage -smtpServer 0.0.0.0 -from passwords@rainbow.com -to enduser@rainbow.com -subject $subject -body $body -bodyasHTML -priority High -Encoding $textEncoding –Attachments $($attachment.FullName)  -ErrorAction Stop
      
          
    • Not sure i understand the html, why -f ($attachment.Name) ?
    • -f ($attachment.name) is required to attach the file to the e-mail, else it won't embed. I think I will have to use the CID method to make it work on iphone because attachments are treated different in outlook vs iphone. Its become pretty complex to get embedded attachments to display correct on the device. See URL below this is going to take some trial and error 
      https://stackoverflow.com/questions/40387292/create-inline-image-that-displays-properly-in-ios-mail-app
    • Any reason why I would not get the test e-mails ? script seems to process with no errors and it defines my e-mail address to receive them. It finds 10 users etc . 
    • No -f $attachment is not required, at least in my understanding.
      
      That is what -attachment is for in the send-mailmessage command.
      
      This video shows how i used attachments with inline images.
      
      https://www.youtube.com/watch?v=iwvQ5tPqgW0
  • The script is not reading from AD
    2 Posts | Last post June 16, 2018
    • Hello i been using the script for the pass 6 mount and today when it ran the report came back as blank. When i ran the scripts it said it can fine any user from AD, yesterday it work fine. I ran it on my test enviarment and get the same result.
      
      can you help me with issues.
      
      Best
    • Start by broadening the search under get-aduser. Remove the filtering.
      
      What does the log show?
      
      Can you run it interactively and see what happens?
      
  • -reportto - Make script include log file data in body of email not just attachment
    2 Posts | Last post June 12, 2018
    • This isn't really a question, I just don't like having to click on the attachment to see the users with expiring passwords when using the reportto option so I made a modification that would have the script add info to the body of the email about who's password is expiring.
      
      $reportBody = "The follwing users have passwords expiring in " + $expireInDays + " days:<br>"
      
      foreach ($notifiedUser in $notifiedUsers) {
      	$reportBody = $reportBody + $notifiedUser.username + " - " + $notifiedUser.name + " expires " + $notifiedUser.Usermessage + "<br>"
      }
      $reportBody = $reportBody + "<br>Password Expiry Report Attached"
    • Nice.
  • Works randomly
    6 Posts | Last post June 11, 2018
    • I have defined Interval 1,2,5,10,15. Last time I've got only message 10 days before password expiration. I was wondering could AD query limit or what generate this problem that I didn't ger pwd expiration message on 1,2,5 and 15 days? 
    • How often do you run the script?
    • Scheduled Daily 09:00 AM
    • Do you have the logs for the days where you think you should have received an email?
    • I enabled loggin and it seems that lines have OK -value, but users will not get email as wanted. If logging is enabled, will emails still sent to the users?
    • Yes they should.
      
      If it says OK the messages may be being blocked by the SMTP server after being submitted.
      
      Have you checked SMTP logs, or anti spam?
  • Email Notification error
    14 Posts | Last post June 08, 2018
    • Now i changed machine to run script and stuck with below error,please help on below:
      PS C:\> C:\Users\3000XXXX\Desktop\PasswordChangeNotification.ps1
      The '<' operator is reserved for future use.
      At C:\Users\3000XXXX\Desktop\PasswordChangeNotification.ps1:178 char:6
      +     < <<<< p> Your Password will expire $messageDays <br>
          + CategoryInfo          : ParserError: (<:OperatorToken) [], ParseExceptio
         n
          + FullyQualifiedErrorId : RedirectionNotSupported
    • You have a typo somewhere in the script.
    • I found the typo error & now able to run the script success fully. 
      Please help me add a PDF file in mail notification.
      Thanks in advance.
    • Try this video.
      
      https://www.youtube.com/watch?v=iwvQ5tPqgW0
    • Thanks for the video link.
      If i add the Send-mailmessage command -in this case receive two mails for each user (One with attachment and other without attachment).
      And if add variable in existing send-mailmessage command line, then receive only one mail without attachment for each user. 
      In shared video link its not very clear where to have attachment variable. As observed the script is different from that i downloaded.
       
    • Set the attachment variable to be the path of the file you want to attach.
      
      You can put that inside the system settings section at the top.
      
      Then simply add -attachments $attachment to any send-mailmessage command you want to have the attachment on.
      
      The video is based on the previous version of the script and i have not redone it as the steps required to make this work are the same.
    • I am able to set attachment path in system setting configuration.I have doubt where to insert the -attachments $attachment to send-mailmessage command. If i simply add  send-mailmessage command line in script as follows (after message body):
      
      <p>Sincerely, <br>
          </p>   
          <p>IT Department <br>
          <span style='font-family:Arial;font-size:9pt;font-style:italic;'>
          </font>"
           
      Send-Mailmessage -smtpServer $smtpServer -from $from -to $testRecipient -subject $Subject-body $body -bodyasHTML -priority High -Encoding $textEncoding -Attachments $attachment
          
          # If Testing Is Enabled - Email Administrator
          if($testing)
          {
              $emailaddress = $testRecipient
          } # End Testing
      
          # If a user has no email address listed
          if(($emailaddress) -eq $null)
      {
              $emailaddress = $testRecipient    
          }# End No Valid Email
          $samLabel = $samAccountName.PadRight($padVal," ")
          try
          {
              if($interval)
              {
                  $daysToExpire = [int]$user.DaysToExpire
                  if(($interval) -Contains($daysToExpire))
                  {
                      if($status)
                      {
                          Write-Output "Sending Email : $samLabel : $emailAddress"
                      }
                      Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailAddress -subject $Subject-body $body -bodyasHTML -priority High -Encoding $textEncoding -Attachments $GUide
                      $user | Add-Member -MemberType NoteProperty -Name SendMail -Value "OK"
      
      This is sending dual mail for the individual user.
    • Can you send me the log file and your script?
    • Both are uploaded here - https://files.fm/u/5fsg7c88 
      (Can't reveal user Id & domain name so i changed) 
    • Can you send the actual log file not the output from the screen.
    • Same is uploaded here - https://files.fm/u/xu6pgtzx. All these users in the log are receiving two mails with same subject line. One mail is with required attachment and other without it.
    • Line 202 is the line sending the duplicate notification.
      
      Line 160 seems to be a new line you added, including the attachment.
      
      So, either remove line 160 and add the attachment to line 202, or remove line 202.
    • Thanks a ton for your support in resolving. Appreciate your efforts. 
      One last query - i added <p><img src=""$image"" height=""50"" Width=""116.5""><br> before  
      line 149, but image is not visible in mail notification. It is only showing a 'X' object in notification. What could be the reason?
    • How did you define $image ?
  • Only three results?
    7 Posts | Last post June 07, 2018
    • Hi Robert!
      
      First of all: Nice tool you made. Really enjoying it!
      
      But I got a problem. First I tried it in a VM - the tool worked. Now I wanted to go live on a Windows Server 2012R2 with more than 400 user in AD. This is what I got:
      Script Loaded
      *** Settings Summary ***
      SMTP Server          : smtp.sendgrid.net
      Expire in Days       : 10
      From                 : XXX
      Logging              : True
      Log Path             : XXX\PasswordExpiration\log.csv
      Testing              : True
      Test Recipient       : XXX
      Report Recipient     : 
      Intervals            : 1 3 5 10
      *************************
      Found 3 User Objects
      Domain Default Password Age: 61
      Process User Objects
      3 Users processed
      0 Users with expiring passwords within 10 Days
      Creating Log File
      Log Output: XXX\PasswordExpiration\log.csv\2018-6-7-9-59-51-PasswordLog.csv
      Script Runtime: 00:00:00.8650753
      
      I tried it with -SearchBase and other lines I found here in comments. Doesn't work. Created a task with another user account, changed GPO to run logon batch / allow local logon - same issue. Tried it manual as domain admin with followin command: PasswordExpiration\PasswordChangeNotification.ps1 -interval 1,3,5,10 -expireInDays 10 - doesn't work, too.
      
      Really would love to get help. Thanks, Robert!
    • If I start Powershell as Administrator to test the script it works. But I created an user account to run the task without Administrator privileges. Doesn't work. :x
    • Have you delegated permissions for that user to read all the user properties?
      https://www.youtube.com/watch?v=xbzxWOarVuk&t=39s
    • Hmpf, yes - I did. 
    • I think I need to get started powershell as Administrator with the service account, but don't know how. 
    • Seems that it works now, but log now says: "Cannot process argument transformation on parameter 'Credential'. Access is denied"
      uff... :D
    • This might help.
      
      https://www.youtube.com/watch?v=_-JHzG_LNvw
  • I am running on a 2016 DC
    3 Posts | Last post June 04, 2018
    • I tried running your script and I get the following error:
      
      PowerShell.exe : Cannot overwrite variable Error because it is read-only or constant.
      At line:1 char:1
      + PowerShell.exe `
      + ~~~~~~~~~~~~~~~~
          + CategoryInfo          : NotSpecified: (Cannot overwrit...ly or constant.:String) [], RemoteException
          + FullyQualifiedErrorId : NativeCommandError
       
      At F:\scripts\PasswordChangeNotification.ps1:282 char:13
      +             $error = $_.Exception.Message
      +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo          : WriteError: (Error:String) [], SessionStateUnauthorizedAccessException
          + FullyQualifiedErrorId : VariableNotWritable
      
      
      I have added a bunch of write-Host statements and it looks like it get to the statements for "Skipped - Interval" but then generates error.  No emails are generated.  Log is generated. $notifiedUsers are displayed.
      
      
      Thoughts about where to look for what might be causing this error?
      
      
    • $error = $_.Exception.Message
      
      It's possible $error is reserved in newer versions of PowerShell ill have to check.
      
      
    • Yes it is, will fix in next version.
      
      Change the lines:
                 $error = $_.Exception.Message
                  Write-Output $error
      
      To:
      
                 $errorMessage = $_.Exception.Message
                  Write-Output $errorMessage
      
131 - 140 of 542 Items