Level 1
0 / 100 XP

Create Password Expiration Notification Script

This script is going to rely on our other lesson which is how to send emails from your company or personal Gmail account with Windows PowerShell. In that lesson, we create a “Send-Mail” function that we will be utilizing in this script.

The complete script is below:

  1. function Send-Email() {
  2. param(
  3. [Parameter(mandatory=$true)][string]$To,
  4. [Parameter(mandatory=$true)][string]$Subject,
  5. [Parameter(mandatory=$true)][string]$Body
  6. )
  7. # Get user credentials
  8. $username = (Get-Content -Path "C:\\Scripts\\gmail_creds.txt")[0]
  9. $password = (Get-Content -Path "C:\\Scripts\\gmail_creds.txt")[1] | ConvertTo-SecureString -AsPlainText -Force
  10. # Create hash for email
  11. $email = @{
  12. from = $username
  13. to = $To
  14. subject = $Subject
  15. smtpserver = "smtp.gmail.com"
  16. body = $Body
  17. credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $password
  18. usessl = $true
  19. verbose = $true
  20. }
  21. Send-MailMessage @email
  22. }
  23. Get all AD Users

  24. $ADUsers = (Get-ADUser -Filter * -Properties mail, msDS-UserPasswordExpiryTimeComputed)
  25. Variables

  26. $DoesNotExpire = 9223372036854775807 # This is the value of msDS-UserPasswordExpiryTimeComputed when the users password is set to never expire
  27. Iterate over all the AD users

  28. foreach($User in $ADUsers) {
  29. # Does the password expire?
  30. if($User.'msDS-UserPasswordExpiryTimeComputed' -ne $DoesNotExpire) {
  31. # Find out how long until the password expires
  32. $ExpirationDate = [DateTime]::FromFileTime($User.'msDS-UserPasswordExpiryTimeComputed')
  33. $Difference = New-TimeSpan -Start (Get-Date) -End $ExpirationDate

42.…