Guest User

Password Expiry Email Notification

a guest
May 30th, 2017
956
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.98 KB | None | 0 0
  1. <#
  2. .Synopsis
  3. Script to Automated Email Reminders when Users Passwords due to Expire.
  4. .DESCRIPTION
  5. Script to Automated Email Reminders when Users Passwords due to Expire.
  6. Robert Pearman (Cloud & Data Center MVP)
  7. WindowsServerEssentials.com
  8. Version 2.3 March 2017
  9. Requires: Windows PowerShell Module for Active Directory
  10. For assistance and ideas, visit the TechNet Gallery Q&A Page. http://gallery.technet.microsoft.com/Password-Expiry-Email-177c3e27/view/Discussions#content
  11. .EXAMPLE
  12. PasswordChangeNotification.ps1 -smtpServer mail.domain.com -expireInDays 21 -from "IT Support <support@domain.com>" -Logging -LogPath "c:\logFiles" -testing -testRecipient support@domain.com
  13. .EXAMPLE
  14. PasswordChangeNotification.ps1 -smtpServer mail.domain.com -expireInDays 21 -from "IT Support <support@domain.com>"
  15. #>
  16. param(
  17. # $smtpServer Enter Your SMTP Server Hostname or IP Address
  18. [Parameter(Mandatory=$True,Position=0)]
  19. [ValidateNotNull()]
  20. [string]$smtpServer,
  21. # Notify Users if Expiry Less than X Days
  22. [Parameter(Mandatory=$True,Position=1)]
  23. [ValidateNotNull()]
  24. [int]$expireInDays,
  25. # From Address, eg "IT Support <support@domain.com>"
  26. [Parameter(Mandatory=$True,Position=2)]
  27. [ValidateNotNull()]
  28. [string]$from,
  29. [Parameter(Position=3)]
  30. [switch]$logging,
  31. # Log File Path
  32. [Parameter(Position=4)]
  33. [string]$logPath,
  34. # Testing Enabled
  35. [Parameter(Position=5)]
  36. [switch]$testing,
  37. # Test Recipient, eg recipient@domain.com
  38. [Parameter(Position=6)]
  39. [string]$testRecipient,
  40. [Parameter(Position=7)]
  41. [switch]$status
  42. )
  43. ###################################################################################################################
  44. $start = [datetime]::Now
  45. $midnight = $start.Date.AddDays(1)
  46. $timeToMidnight = New-TimeSpan -Start $start -end $midnight.Date
  47. $midnight2 = $start.Date.AddDays(2)
  48. $timeToMidnight2 = New-TimeSpan -Start $start -end $midnight2.Date
  49. # System Settings
  50. $textEncoding = [System.Text.Encoding]::UTF8
  51. $today = $start
  52. # End System Settings
  53.  
  54. # Get Users From AD who are Enabled, Passwords Expire and are Not Currently Expired
  55. Import-Module ActiveDirectory
  56. $padVal = "20"
  57. Write-Output "Script Loaded"
  58. Write-Output "*** Settings Summary ***"
  59. $smtpServerLabel = "SMTP Server".PadRight($padVal," ")
  60. $expireInDaysLabel = "Expire in Days".PadRight($padVal," ")
  61. $fromLabel = "From".PadRight($padVal," ")
  62. $testLabel = "Testing".PadRight($padVal," ")
  63. $testRecipientLabel = "Test Recipient".PadRight($padVal," ")
  64. $logLabel = "Logging".PadRight($padVal," ")
  65. $logPathLabel = "Log Path".PadRight($padVal," ")
  66. if($testing)
  67. {
  68. if(($testRecipient) -eq $null)
  69. {
  70. Write-Output "No Test Recipient Specified"
  71. Exit
  72. }
  73. }
  74. if($logging)
  75. {
  76. if(($logPath) -eq $null)
  77. {
  78. $logPath = $PSScriptRoot
  79. }
  80. }
  81. Write-Output "$smtpServerLabel : $smtpServer"
  82. Write-Output "$expireInDaysLabel : $expireInDays"
  83. Write-Output "$fromLabel : $from"
  84. Write-Output "$logLabel : $logging"
  85. Write-Output "$logPathLabel : $logPath"
  86. Write-Output "$testLabel : $testing"
  87. Write-Output "$testRecipientLabel : $testRecipient"
  88. Write-Output "*".PadRight(25,"*")
  89. $users = get-aduser -filter {(Enabled -eq $true) -and (PasswordNeverExpires -eq $false)} -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet, EmailAddress | where { $_.passwordexpired -eq $false }
  90. # Count Users
  91. $usersCount = ($users | Measure-Object).Count
  92. Write-Output "Found $usersCount User Objects"
  93. # Collect Domain Password Policy Information
  94. $defaultMaxPasswordAge = (Get-ADDefaultDomainPasswordPolicy -ErrorAction Stop).MaxPasswordAge.Days
  95. Write-Output "Domain Default Password Age: $defaultMaxPasswordAge"
  96. # Collect Users
  97. $colUsers = @()
  98. # Process Each User for Password Expiry
  99. Write-Output "Process User Objects"
  100. foreach ($user in $users)
  101. {
  102. $Name = $user.Name
  103. $emailaddress = $user.emailaddress
  104. $passwordSetDate = $user.PasswordLastSet
  105. $samAccountName = $user.SamAccountName
  106. $pwdLastSet = $user.PasswordLastSet
  107. # Check for Fine Grained Password
  108. $maxPasswordAge = $defaultMaxPasswordAge
  109. $PasswordPol = (Get-AduserResultantPasswordPolicy $user)
  110. if (($PasswordPol) -ne $null)
  111. {
  112. $maxPasswordAge = ($PasswordPol).MaxPasswordAge.Days
  113. }
  114. # Create User Object
  115. $userObj = New-Object System.Object
  116. $expireson = $pwdLastSet.AddDays($maxPasswordAge)
  117. $daysToExpire = New-TimeSpan -Start $today -End $Expireson
  118. # Round Up or Down
  119. if(($daysToExpire.Days -eq "0") -and ($daysToExpire.TotalHours -le $timeToMidnight.TotalHours))
  120. {
  121. $userObj | Add-Member -Type NoteProperty -Name UserMessage -Value "today."
  122. }
  123. if(($daysToExpire.Days -eq "0") -and ($daysToExpire.TotalHours -gt $timeToMidnight.TotalHours) -or ($daysToExpire.Days -eq "1") -and ($daysToExpire.TotalHours -le $timeToMidnight2.TotalHours))
  124. {
  125. $userObj | Add-Member -Type NoteProperty -Name UserMessage -Value "tomorrow."
  126. }
  127. if(($daysToExpire.Days -ge "1") -and ($daysToExpire.TotalHours -gt $timeToMidnight2.TotalHours))
  128. {
  129. $days = $daysToExpire.TotalDays
  130. $days = [math]::Round($days)
  131. $userObj | Add-Member -Type NoteProperty -Name UserMessage -Value "in $days days."
  132. }
  133. $daysToExpire = [math]::Round($daysToExpire.TotalDays)
  134. $userObj | Add-Member -Type NoteProperty -Name UserName -Value $samAccountName
  135. $userObj | Add-Member -Type NoteProperty -Name Name -Value $Name
  136. $userObj | Add-Member -Type NoteProperty -Name EmailAddress -Value $emailAddress
  137. $userObj | Add-Member -Type NoteProperty -Name PasswordSet -Value $pwdLastSet
  138. $userObj | Add-Member -Type NoteProperty -Name DaysToExpire -Value $daysToExpire
  139. $userObj | Add-Member -Type NoteProperty -Name ExpiresOn -Value $expiresOn
  140. $colUsers += $userObj
  141. }
  142. $colUsersCount = ($colUsers | Measure-Object).Count
  143. Write-Output "$colusersCount Users processed"
  144. $notifyUsers = $colUsers | where { $_.DaysToExpire -le $expireInDays}
  145. $notifiedUsers = @()
  146. $notifyCount = ($notifyUsers | Measure-Object).Count
  147. Write-Output "$notifyCount Users to notify"
  148. foreach ($user in $notifyUsers)
  149. {
  150. # Email Address
  151. $samAccountName = $user.UserName
  152. $emailAddress = $user.EmailAddress
  153. # Set Greeting Message
  154. $name = $user.Name
  155. $messageDays = $user.UserMessage
  156. # Subject Setting
  157. $subject="Your password will expire $messageDays"
  158. # Email Body Set Here, Note You can use HTML, including Images.
  159. $body ="
  160. <font face=""verdana"">
  161. Dear $name,
  162. <p> Your Password will expire $messageDays<br>
  163. To change your password on a PC press CTRL ALT Delete and choose Change Password <br>
  164. <p> If you are using a MAC you can now change your password via Web Mail. <br>
  165. Login to <a href=""https://mail.domain.com/owa"">Web Mail</a> click on Options, then Change Password.
  166. <p> Don't forget to Update the password on your Mobile Devices as well!
  167. <p>Thanks, <br>
  168. </P>
  169. IT Support
  170. <a href=""mailto:support@domain.com""?Subject=Password Expiry Assistance"">support@domain.com</a> | 0123 456 78910
  171. </font>"
  172.  
  173. # If Testing Is Enabled - Email Administrator
  174. if($testing)
  175. {
  176. $emailaddress = $testRecipient
  177. } # End Testing
  178.  
  179. # If a user has no email address listed
  180. if(($emailaddress) -eq $null)
  181. {
  182. $emailaddress = $testRecipient
  183. }# End No Valid Email
  184. $samLabel = $samAccountName.PadRight($padVal," ")
  185. if($status)
  186. {
  187. Write-Output "Sending Email : $samLabel : $emailAddress"
  188. }
  189. try
  190. {
  191. Send-Mailmessage -smtpServer $smtpServer -from $from -to $emailaddress -subject $subject -body $body -bodyasHTML -priority High -Encoding $textEncoding -ErrorAction Stop
  192. $user | Add-Member -MemberType NoteProperty -Name SendMail -Value "OK"
  193. }
  194. catch
  195. {
  196. $errorMessage = $_.exception.Message
  197. if($status)
  198. {
  199. $errorMessage
  200. }
  201. $user | Add-Member -MemberType NoteProperty -Name SendMail -Value $errorMessage
  202. }
  203. $notifiedUsers += $user
  204. }
  205. if($logging)
  206. {
  207. # Create Log File
  208. Write-Output "Creating Log File"
  209. $day = $today.Day
  210. $month = $today.Month
  211. $year = $today.Year
  212. $date = "$day-$month-$year"
  213. $logFileName = "$date-PasswordLog.csv"
  214. if(!($logPath.EndsWith("\")))
  215. {
  216. $logFile = $logPath + "\"
  217. }
  218. $logFile = $logFile + $logFileName
  219. Write-Output "Log Output: $logfile"
  220. $notifiedUsers | Export-CSV $logFile
  221. }
  222. $notifiedUsers | select UserName,Name,EmailAddress,PasswordSet,DaysToExpire,ExpiresOn | sort DaystoExpire | FT -autoSize
  223.  
  224.  
  225. $stop = [datetime]::Now
  226. $runTime = New-TimeSpan $start $stop
  227. Write-Output "Script Runtime: $runtime"
  228. # End
Add Comment
Please, Sign In to add comment