Send Email Notification with PowerShell Script to AD User’s for Password Change

This article is about using the PowerShell script for AD user password changes. The PowerShell script we’ll discuss is a powerful tool that can automate the notification process and save you time and effort. Let’s dive in and explore how this script works and how you can use it to your advantage.

What is PowerShell Script and How Does it Work?

PowerShell is a scripting language developed by Microsoft that helps automate and manage tasks in Windows environments. It is particularly useful for managing Active Directory (AD) users and can be used to notify users to change their password before expire. PowerShell scripts can be written manually or generated using the PowerShell Integrated Scripting Environment (ISE).

To notify AD users of password changes, PowerShell scripts retrieve the user account information from AD and send email notifications to the users. The script can be customized to include specific information in the email, such as the date and time of the password change, and the user’s username. The script can also be scheduled to run automatically, ensuring that notifications are sent regularly without any manual intervention.

Setting Up the PowerShell Script for Password Change Notification

In order to set up the PowerShell script for password change notifications, follow these steps:

  1. Open PowerShell ISE on your computer.
  2. Copy and paste the following code into the script editor:

Note: The following code is an example and should be modified to fit your specific needs. Make sure to replace the email addresses and other variables with your own information.

########################################################################################

### Module to Store Email Credentials in Window Credential Manager ### 
Install-Module CredentialManager

New-StoredCredential -Target EmailCred -UserName username@domain -Password $XXXXXX@$ -Type Generic -Persist LocalMachine


 Reference Image:

                                                                                    Image 1
 
###### Define the email parameters ######

$smtpServer = “smtp.office365.com” 

## SMTP Server can be changed as per Email Service Provider #

$smtpPort = 587

$importance = “High”


# Get Credentials from Windows Credential Manager # 

$Cred=Get-StoredCredential -Target EmailCred

$password= $cred.GetNetworkCredential().Password

# Create a new SMTP client object and configure it

$smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort)

$smtpClient.EnableSsl = $true

$smtpClient.Credentials = New-Object System.Net.NetworkCredential($username,$password)

######## Day Count 14  ########

# Define the number of days until password expiry 14

$daysUntilExpiration_E1 = 14

# Get the current date

$currentDate = Get-Date

# Calculate the target password expiry date

$targetExpiryDate = $currentDate.AddDays($daysUntilExpiration_E1)

# Get all AD users whose password will expire in 14 days

$users = Get-ADUser -Filter {Enabled -eq $true -and PasswordNeverExpires -eq $false -and PasswordExpired -eq $false} -Properties PasswordLastSet | Where-Object {

$passwordExpiryDate = $_.PasswordLastSet.AddDays((GetADDefaultDomainPasswordPolicy).MaxPasswordAge.TotalDays)

    $passwordExpiryDate -ge $currentDate -and $passwordExpiryDate -le $targetExpiryDate

}

# Loop through each user and send them an email notification

for each ($user in $users) {

# Define the email subject and body

$subject = “Your password will expire in $daysUntilExpiration_E1 days”

$body = “Dear $($user.Name),`n`nYour password will expire in $daysUntilExpiration_E1 days. Please change your password as soon as possible.` please open Self Service Password Reset(SSPR) Portal URL: https://sspr.example.local/RDWeb/pages/en-US/password.aspx`n`nBest regards,` nIT Admin”

$from = $username

$to = Get-ADUser -Identity $user -Properties EmailAddress | Select-Object -ExpandProperty EmailAddress

# Generate Email Message #

$mailMessage = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $body)

 # Set the email importance

$mailMessage.Headers.Add(“X-Priority”, $importance)

# Send the email

$smtpClient.Send($mailMessage)

}

########################################################################################

  1. Modify the variables in the code to fit your specific needs. Make sure to replace the email addresses and other variables with your own information.
  2. Save the script with a .ps1 extension, such as “password_change_notification.ps1”.

Once the script is set up, it can be run manually or automated to run at regular intervals using the Task Scheduler. In the next section, we will discuss how to customize the PowerShell script for your needs.

Customizing the PowerShell Script for Your Needs

The PowerShell script for password notification can be customized to meet your specific needs for AD user password management. Here are some examples of how the script can be modified:

CustomizationDescription
Notification MessageYou can modify the notification message to include additional information, such as the password expiration date or instructions for resetting the password.
Email RecipientsYou can specify the email recipients for the notification, such as the user’s manager or a member of the IT department.
Frequency of NotificationsYou can adjust the frequency of notifications to meet your organization’s password policy, such as sending notifications 7 days before password expiration.

Customizing the PowerShell script requires some knowledge of scripting and AD user management. However, the script is well-commented and easy to follow, making it accessible to those with intermediate-level PowerShell skills.

Note: It is recommended to test any customizations to the PowerShell script before implementing them in a production environment.

Testing the PowerShell Script for Password Change Notification

After setting up and customizing your PowerShell script for password change notifications, it’s important to test it to ensure it works correctly.

Here are the steps to test the PowerShell script: Open PowerShell and run the script by typing its file path, followed by “.\scriptname.ps1” (replace “script name” with the actual name of your script).

Reference Image


                                                                                    Image 2

Sample Test Output

  • Verify that you receive a notification in the format you specified in the script. Check that the notification contains the correct information.
  • If you don’t receive a notification, check the script’s output for any errors or warnings. If you see any errors, troubleshoot them by reviewing the script’s code, SMTP Setting & ensuring that all necessary parameters.

If you continue to experience issues with the script after troubleshooting, consider seeking assistance from PowerShell forums or consulting with a professional IT administrator.

Automating Password Change Notification with PowerShell Script

Automating the PowerShell script for password notifications can save time and reduce the risk of human error. This can be achieved by setting up a task scheduler in Windows to run the PowerShell script at regular intervals, such as daily or weekly.

To set up a task scheduler, follow these steps:

StepDescription
1Open the Windows Task Scheduler. Click Start, type Task Scheduler, and press Enter.
2Click Create Task in the Actions pane on the right.
3Enter a name for the task and select the Run with highest privileges checkbox.
4Go to the Triggers tab and click New.
5Select the frequency and time for the task to run and click OK.
6Go to the Actions tab and click New.
7Enter the location of the PowerShell script in the Program/Script field and enter any necessary arguments in the Add arguments field.
8Click OK to save the task.

Reference Images for Task Scheduler:
  

                                                                                             Image 3  

                        
                                                                                        Image 4
 
Once the task is set up, the PowerShell script will run automatically at the scheduled intervals. This ensures that notifications are sent to users in a timely and consistent manner without the need for manual intervention.

It is important to regularly test the script and ensure that it is up to date with any changes to the AD environment. This can help prevent any potential issues and ensure that the script continues to run smoothly.

Benefits of Using PowerShell Script for Password Change Notification

The use of PowerShell script for password change notification in AD user management comes with numerous benefits. These include:

BenefitDescription
Improved SecurityBy notifying users of password changes, the risk of unauthorized access to sensitive data is reduced.
Increased EfficiencyManually notifying users of password changes can be time-consuming and error-prone. By automating this process with a PowerShell script, IT teams can save time and reduce the risk of mistakes.
FlexibilityThe PowerShell script can be customized to meet the specific needs of an organization, whether that means filtering notifications based on user groups or modifying the email template.
Cost SavingsUsing a PowerShell script for password change notifications can eliminate the need for expensive third-party solutions.

By utilizing a PowerShell script for password change notifications, organizations can improve their security posture, streamline IT processes, and save money. It is a versatile tool that can be tailored to meet the unique needs of any organization.

Best Practices for Password Change Notification with PowerShell Script

Using a PowerShell script for password change notifications can greatly improve AD user password management, but it’s important to follow best practices to get the most out of the script. Here are some tips to help you use the PowerShell script effectively:

1. Ensure Notifications Are Sent to the Correct Recipients
2. Test the Script Before Implementation
3. Follow IT Security Best Practices
4. Document Your Use of the Script

Frequently Asked Questions about PowerShell Script for Password Change Notification

If you have any questions about using the PowerShell script for password change notifications, you may find the answers in this FAQ section.

How often should a password change notification be sent?

This depends on the security policies of your organization. However, it is recommended that notifications are sent at least once a week to ensure that users are aware of password changes.

Is it possible to exclude certain users from receiving password change notifications?

Yes, you can modify the PowerShell script to exclude certain users, such as service accounts or administrative accounts, from receiving password change notifications.

Is it safe to automate password change notifications with the PowerShell script?

Yes, automating password change notifications with the PowerShell script is safe as long as you follow best practices, such as ensuring that notifications are sent securely and to the correct recipients.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top