Compartir a través de


Auto-Mail Expiring Domain Accounts

 

               I was looking online for automating the task of domain account expiry notification for one my customers to provide as a reference and found a few which were using quest based PowerShell scripts. The customer required this due to a large number of outsourced business partners in their ecosystem. At the moment the domain accounts given to partner employees working at their different branch offices were valid only for 6 months after which it was to be renewed after approval from the business leads and HR. They wanted a process in which the end user ( partner employees ) were notified via an automated email mentioning the date when their account was to expire and a brief summary of the process to have it extended.

    Here is when I thought I could use the power of PowerShell. Many online resources took me through using Quest based cmd-lets and then I used the same ideas but with built-in cmd-lets to do the same job.

There are 2 phases I planned to tackle this

1. Build a PowerShell script to find all domain accounts expiring within a specified time ( no. of days ).

2. Schedule a task to run the Power Shell script once every x no. of days based on the requirement.  

Phase 1 : Power Shell script

######Script Begins Here

#####Author: Jithesh Raj

 

import-module Activedirectory

#If you are using Windows 8 or server 2012 you do not require to import-modules as PS 3.0 will do that for you automatically.

Search-ADAccount -AccountExpiring -TimeSpan 30.00:00:00 | Export-csv "C:\scripts\users.csv"

#Please change the no. of days in -TimeSpan switch to find all users whose account will expiry in that many days

import-csv "C:\Scripts\users.csv" | Get-ADUser -Identity {$_.Samaccountname} -Properties displayname,mail,samaccountname,userprincipalname,AccountExpirationDate | Select-Object Name,Samaccountname,Mail,displayname,AccountExpirationDate |ForEach-Object {

# Variables defined below must be changed in your environment accordingly.

$smtp= "mail.contoso.com" # Enter your smtp server

$from= "IThelpdesk@contoso.com" # Enter your from address

$subject= "Account Expiry Notification" # Enter your email subject

$email= $_.mail

$name= $_.displayname

$date= $_.AccountExpirationDate

Function GetMsgBody {

Write-Output @"

<p>Dear $name,</p>

Your windows account is going to expire on $date.<br/>

Kindly contact your business lead to request for extension.<br/>

<br/>

<br/>

Kind Regards,<br/>

IT Helpdesk

"@

}

[string]$body= GetMsgBody

 # Please change the body of the mail accordingly

#Execute PowerShell's Send-MailMessage Function

Send-MailMessage -BodyAsHtml:$true -Body $body -To $email -From $from -SmtpServer $smtp -Subject $subject

}

Send-MailMessage -To DomainsHelpdesk@contoso.com -From IThelpdesk@contoso.com -Smtpserver $smtp -attachment "C:\Scripts\users.csv" -subject $Subject

# Last line sends an additional email to the domains helpdesk team to track the accounts that are expiring for hosusekeeping purposes. 

##################################Script Ends Here 

The above lines of script starting can be copied to a notepad and saved as Email-Expiring-Accounts.ps1 to the machine from where the script is to be run.

Phase 2: Scheduling the script  

How to Schedule the script to run using Task Scheduler

1.       Logon to machine to schedule the task from.

2.       Create a Folder by name C:\scripts since it is used in the script. If you chose to use an alternate location please change it in the script as well. The script obtained from above steps must be copied to this folder.

3.       Start Task Scheduler

4.       Right Click Task Scheduler Library and create a New Folder by Email-Expiring-Accounts.

5.      You may also create an additional folder by name Active Directory to simply the script based on technology if you may have additional script in the future.

6.       Right click to create a new task

7.  The task will look as below. Additional details can be populated in the description field.

 
  

 8. Click on the Triggers tab and configure accordingly. This task is configured to run every week on Sunday at 7 AM local time on the server.

 

  

 9.  The Action of the Scheduled Task is to run the following command:

      1. Program/script:
        • C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
      2. Add arguments:
        • -command "& ' C:\Scripts\Email-Expiring-Accounts.ps1'"

 

 

Now the script is ready to run and will automatically send an email using the account specified in the script to individual users whose account is set to expire in the next 30 days. The schedule task can be run using a local administrator account on the machine it is being run from and does not need any domain wide elevated privileges.

Disclaimer The sample scripts are not supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.

 

Email-ExpiringADAccounts.ps1

Comments

  • Anonymous
    January 01, 2003
    @Ashish - I hope you understand that expiring accounts is different from password expiry.
    In your case you could do the below.
    On a Win dows 7 Client Open PowerShell as Administrator
    Import-Module ActiveDirectory
    $days=(Get-date).AddDays(-30)
    Get-AdUser -Filter { (passwordlastset -notlike "*" -OR Passwordlastset -lt $days) } -properties * | select name,mail,distinguishedname | export-csv C:Users_WithPassowrd_Expiring_In30days.csv -notypeinformation
  • Anonymous
    March 05, 2015
    This script does not populate the csv file. It completes with no errors. I am not trying to email anything for now, just want to have the csv file populated with expiring passwords (ie 30 days). Did it work for you?
  • Anonymous
    April 07, 2015
    Works nicely for me! Thanks
  • Anonymous
    September 08, 2015
    thanks I will have a look into this
  • Anonymous
    December 31, 2015
    Thanks a lot.. it is working for me
  • Anonymous
    March 25, 2016
    If you could also list the expiring account's manager in the email that would be great. Once the email is generated I have to figure out the managers responsible for the account and ask for permission to extend account. Excellent set of instructions by the way!!!