Automatic Email Notification to Administrator about Inactive Accounts in Active Directory (PowerShell)

Introduction

The goal of this script is to automatic email notification to Administrator about Inactive accounts in Active Directory.

Scenarios

For management administrators always intend to identify the inactive user/computer accounts that have not logged on the domain for a certain period of time, then they could determine to disable, delete or remove these accounts. Rather than administrator manually finding out inactive accounts when he needed, automatically generating an inactive user/computer accounts report and sending a email notification to administrator would be much better.

Script

This script contains one advanced functions Send-OSCInactiveUsersEmail, you can use this script in the following way:

Step1: Open the script file with Notepad. Scroll down to the end of the script file, and then add the example command which you want to run. Then save the file.
Example: Send-OSCInactiveUsersEmail -From user1@Domain.com -To admin1@Domain.com,admin2@Domain.com -SMTPServer smtp.domain.com -InActiveDays 53 -UserName user1 -Password Password

Step2: Create a scheduled task to run that PowerShell script. In action option, you can do as following.

Note the argument "-file" should be with the script path. And about scheduled task, there is a reference.

Use the Windows Task Scheduler to Run a Windows PowerShell Script

Here are some code snippets for your references. To get the complete script sample, please click the download button at the beginning of this page. 

PowerShell
Edit|Remove
$Body = GetInactiveUsers $InActiveDays  
#Send the mail to Adminsitrators 
If($Body) 
{ 
    $SMTPClient = New-Object Net.Mail.SMTPClient($SMTPServer)   
    $SMTPClient.EnableSSL = $true  
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password);  
    $emailMessage = New-Object System.Net.Mail.MailMessage 
    $emailMessage.From = "$From" 
    Foreach($EmailTo in $To) 
    { 
        $emailMessage.To.Add($EmailTo) 
    } 
    $emailMessage.Subject = "Inactive Users in $InActiveDays Days." 
    $emailMessage.IsBodyHTML = $True 
    $emailMessage.Body = $Body 
    $SMTPClient.Send($emailMessage) 
}

Prerequisite

Windows Server 2008R2 or higher version