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.

4.6 Star
81,440 times
Add to favorites
Active Directory
E-mail Twitter Digg Facebook
Sign in to ask a question

  • Scheduled Task Interval Failure
    2 Posts | Last post April 18, 2019
    • Robert,
      This is working fantastically from powershell ISE but from a scheduled task the interval parameter is failing.  Writing to the logfile, each line finishes with ,"Skipped - Interval".
      I'm running powershell.exe with the following argument:
      -file c:\scripts\scheduled\AD-User-Password-Expire-Notification\PasswordChangeNotification.ps1 -smtpServer -expireInDays 14 -from "Service Desk <>" -Logging -LogPath "c:\scripts\logfiles\Password-reset-reminder" -testing -testRecipient -interval 1,3,5,7,14
      Followed advice of an earlier poster I tried wrapping the command with "" and parameters wrapped with ''.  This actually failed to run.
      Any ideas what I maybe doing wrong?
    • lol.  silly error.  changed -file for -command.  all good.  
  • Cannot validate argument on parameter 'To'.
    6 Posts | Last post April 13, 2019
    • Hey Robert,  I have configured and tested w/o issue.  I receive my test notifications and all looks great.  When I go to run this live, I am receiving the following error when attempting to send to a user:
      Cannot validate argument on parameter 'To'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
      No email goes out.  I do not see a To parameter anywhere in the script however.  
      Where do I need to look?  or update?
    • -to is a parameter in Send-MailMessage, it is set to use $emailAddress.
      So, i would guess that one or more of your users does not have an emailaddress stored in Active Directory.
    • I am assuming you are referring to the 'mail' attribute in AD correct?  I show in the report that there are email addresses populated.  Here is one example:
      in 5 days.	zografoss	Sheila Zografos	9/10/2018 7:06	5	3/9/2019 7:06	Cannot validate argument on parameter 'To'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
      The EmailAddress column is showing the correct address for the user. 
    • Are you able to use Send-MailMessage on it's own to that recipient?
    • Yes I am able to send test messages using Send-MailMessage through the relay.
    • Hey Robert.  So I went back and sent a test email from the script w/o any modifications and was able to successfully send.  
      So started reviewing each modification from the originally edited script, and line 54 - the $testing string, I had = "Disabled".  I removed the = "Disabled" from this line and retested and was successful in sending the emails!  
      Not sure why this line would have an affect but it is working now.  Thanks for your time on this!
  • if no expiring password is found no log is written
    1 Posts | Last post April 11, 2019
    • if no user are found the script thrown this error:
      You cannot call a method on a null-valued expression.
      At c:\scripts\PasswordChangeNotification.ps1:228 char:41
      +     $samLabel = $samAccountName.PadRight <<<< ($padVal," ")
          + CategoryInfo          : InvalidOperation: (PadRight:String) [], RuntimeException
          + FullyQualifiedErrorId : InvokeMethodOnNull
      Add-Member : Cannot bind argument to parameter 'InputObject' because it is null.
      At c:\scripts\PasswordChangeNotification.ps1:266 char:31
      +             $user | Add-Member <<<<  -MemberType NoteProperty -Name SendMail -Value "OK"
          + CategoryInfo          : InvalidData: (:) [Add-Member], ParameterBindingValidationException
          + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.AddMemberCommand
      Creating Log File
      Log Output: .\11-4-2019-PasswordLog.csv
      Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null.
      At c:\scripts\PasswordChangeNotification.ps1:296 char:32
      +     $notifiedUsers | Export-CSV <<<<  $logFile
          + CategoryInfo          : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
          + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCommand
  • Method invocation failed because [System.Int32] does not contain a method named 'split'.
    5 Posts | Last post April 11, 2019
    • Hi there,
      I have implemented this script on several servers. On 1 server I see this error in the logfile and the e-mail is not being send.
      What is missing or wrong overhere?
    • Any more info? Line number of the error, full error text? OS of the server?
    • I found the reason. The split is this line:
         if(($interval.split(",")) -Contains($daysToExpire.toString()))
      That isn't part of the script but on some servers the orginal line:
         if(($interval) -Contains($daysToExpire))
      Won't work because when using more days in the interval parameter you need the spplit. I thing its different per OS.
      That solution was posted earlier.
    • And when not using the split, it will not e-mail. It will keep saying in the log in the collum SendMail just an OK, nothing more. And the interval has got 5.
    • I think that depends how you pass the interval array into the script.
      What is the full command you use to run the script?
  • SMTP Issue while Testing
    4 Posts | Last post April 09, 2019
    • Hi there,
      Having issues getting the e-mail portion to work with g-mail. We will most likely use Office 365 smtp servers but I just wanted to get this working before I show it to my team.
      SMTP Server          :
      Expire in Days       : 21
      From                 :
      Logging              : True
      Log Path             : c:\logFiles
      Testing              : True
      Test Recipient       :
      Report Recipient     : 
      Intervals            : 
      Getting this error:
      The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. g1sm7204905ywf.0 - gsmtp
      I know my credentials are right, and I've followed your YT tutorial on creating the smtp.txt file as well as making it a securestring.
      Any thoughts?
      I've also added the PORT and USESSL portions to test and I'm not getting in my e-mail. Even without the port type, the error above is asking for some STARTTLS command.
      Send-Mailmessage -smtpServer $smtpServer -from $from -to $reportTo -subject $reportSubject -body $reportbody -bodyasHTML -priority High -Encoding $textEncoding -Attachments $logFile -Credential $credential Port 587 -UseSsl -ErrorAction Stop 
    • Have a look at the question on December 2nd 2018, that has the solution you need.
    • I only see questions from Dec 11 then it jumps to Nov 29. I'm missing something here. Please help.
    • Sorry don't know what happened, it was December 18th.
       [System.Net.ServicePointManager]::SecurityProtocol = 'TLS12' 
      You need to set the above prior to the sending the message, so i have added it to 'system settings'..
      # System Settings
      $textEncoding = [System.Text.Encoding]::UTF8
      $today = $start
      # Set TLS Version, used with SMTP Authentication
      [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
      # End System Settings
  • Remove top line that is coming up in CSV report being emailed
    4 Posts | Last post April 07, 2019
    • Hello! Thank you so much for creating and maintaining/improving this script. It is used by me and I think it is one amazing script.
      One question - The is one line being added at the top of the CSV report which is emailed out by your script. The top of the report looks like this:
      #TYPE System.Object							
      UserMessage	UserName	Name	EmailAddress	PasswordSet	DaysToExpire	ExpiresOn	SendMail
      Is there a way to have the "#TYPE System.Object" removed the report? I located this info which may be of help to you:
      Thank you!
    • That looks quite convoluted to me.
      You can probably make this a bit prettier...
      $csvNew = "new-report.csv"
      $oldCSV = Get-Content "report.csv"
      $oldCSV = $oldCSV.trim("#TYPE System.Object")
      $oldCSV = $oldCSV | where { $_ -ne "" }
      New-Item $csvNew -ItemType file -Force
      Add-Content $csvNew $oldCSV
    • Can you tell me where in the latest version of your script I would need to place those lines? Thank you!
    • Right before the line where the report is sent.
  • Not sending email when task scheduler, or batch file used to run
    3 Posts | Last post March 26, 2019
    • I did see other comments that this issue has happened to others, I don't know If I saw an answer. I can run the script from a PowerShell console, it sends email to users with expiring accounts, but when using it with task scheduler, it logs the email as "skipped interval" I am calling from a batch file, using this syntax
      cd C:\Pscript
      powershell.exe -file C:\Pscript\PasswordChangeNotification.ps1 -smtpServer [FQDN of internal server name] -expireInDays 10 -from "Password Change <>" -Logging -LogPath "c:\SMTPFiles" -reportTo -interval 0,1,2,5,6,7,8,10
      any comments to what is my error would assist greatly, thank you in advance
    • The only time I saw "Skipped interval" was when my user was within the 10 days but was on day 4 which is not specified in the -interval command. The log file should show you this.  Also when you run from the TS that its running as the same user that was used through the other steps. Below is what is in my task scheduler, I had to remove the "" and replace them with '' inside the string while keeping the "" on the whole string.
      -command "C:\scripts\PasswordChangeNotification.ps1 -smtpServer smtp.mail.server.example -expireInDays 10 -from 'IT Support <>' -Logging -LogPath 'c:\logFiles' -interval 1,2,3,5,7,10"
    • I think that may have solved it, the sending address was a group, I have changed it to a user that can be added to the TS, I have run the script from explorer, it would fail this way prior. thank you
  • only 1 user Object Found
    2 Posts | Last post March 22, 2019
    • Ran script and it is only finding 1 user object. 
      I then tried running it as administrator and now it shows 28 user objects. However this domain has 100+ user accounts. It is also saying 0 users to notify when a manual report shows users will expire tomorrow. 
      Thank you for your assistance. 
    • Answering my own question.. Basically the script was working fine I had a misconception about the company 28 user objects were correct and so was the 0 notifications for my set time of 15 days. However I will share some new info I was able to change the smtp port for so this would work on an Azure server. Added in the Port parameter and moved the other parameters down.
          # $smtpServer Enter Your SMTP Server Hostname or IP Address 
          # $Port Enter Your SMTP Server port number 
          # Notify Users if Expiry Less than X Days 
          # From Address, eg "IT Support <>" 
      ect. res of the Param( section is the same just the Position numbers moved up one. 
      With this change the following command works. 
      Powershell.exe -ExecutionPolicy Bypass c:\PasswordExpire\PasswordChangeNotification.ps1 -smtpServer -Port 2500 -expireInDays 15 -from
  • Send Mail Failure
    2 Posts | Last post March 22, 2019
    • I apologize if this has been answered before, but I did not see it posted here.
      I am unable to get the send mail function to work correctly. I've made a few different modifications, but I continue to get this error even with the 'stock' script downloaded from here.
      "An invalid character was found in the mail header: '<'."
      I can't seem to find which '<' is causing the send mail piece to have issues. Have you seen this before?
    • Please disregard. I was simply missing the trailing '>' on the From address...
  • Get-ADDefaultDomainPasswordPolicy may not work for AWS provisioned domains
    1 Posts | Last post March 16, 2019
    • Hi!
      Just wanted to let you know that AWS doesnt' allow to modify default domain policy in their provisioned Windows AD. Instead they only give you permissions to administer only one OU so the Get-ADDefaultDomainPasswordPolicy always returns 42 days.
      Apparently they have something blocking the Get-AduserResultantPasswordPolicy too! despite the domain level is windows2012r2
      so I had to work around that and came to a solution like that:
      $defaultMaxPasswordAge = [convert]::ToInt32((net accounts | ForEach-Object { if ($_ -match "^Maximum password age \(days\):\s+(\d+)$"){$Matches.1}}),10)
      this always returns the correct policy set by the domain group policy applied to the OU server in.
      that also works great on the domain level windows2008
41 - 50 of 537 Items