Sunday, December 25, 2016

Email Address Change Monitor

This Script has been Written to fullfil one of the App Team request, Here is the requirement:

  • For any user if Primary SMTP address changes, a notification to be sent to them.

  • Alert notification should include the Previous & Changed value.

  • Format should be CSV.


They require it as they need to update the details in the Application if Primary SMTP address alters.

Here is the powershell magic :)

Extract the Zip file from below link



Update the .ps1 file variables:

$limit = (Get-Date).AddDays(-60) #for report recycling

$email1 = "VikasS@labtest.com"

$from = "EmailAddressChange@labtest.com"

$smtpserver = "smtpserver"

Note: Script is using CustomAttribute11 & matching it to $regex = '^\d+$' (integer) i.e. all mailboxes that have employeeid.

This can be changed as per your organization.

First time when the script is run it creates a State-Email.csv file, this is the state file and on next run it compares the newly fetched data with the previous state file to capture the changes which it sends to the specified email in .csv format.



Transcript will be stored in Logs folder & report will be kept inside Report , these will get recycled every 60 days.

Create a schedule Task to run it daily or as per your requirements.(Note: don't forget to fill start in field when scheduling the batch file)



Note: Script has been tested with Exchange 2010 but should work with other versions as well, just change the shell parameter.

Exchange management Shell is a requirement for this script.

 


<#     
    .NOTES 
    =========================================================================== 
     Created on:       12/8/2016 4:19 PM 
     Created by:       Vikas Sukhija 
     Organization:      
     Filename:         EmailAddressChange.ps1 
    =========================================================================== 
    .DESCRIPTION 
        This Script will monitor changes in Primary SMTP address of Users, 
        if there is a change then responsible team will be notified. 
#>
 
################Add Modules Exchange############################# 
$error.clear() 
If ((Get-PSSnapin | where { $_.Name -match "Microsoft.Exchange.Management.PowerShell.E2010" }) -eq $null

    Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 

 
###############ADD Logs & Variables################################ 
$date1 = get-date -format d 
$date1 = $date1.ToString().Replace("/""-"
$time = get-date -format t 
 
$time = $time.ToString().Replace(":""-"
$time = $time.ToString().Replace(" """
 
$log = (Get-Location).Path + "\Logs" + "\" + "Processed_PS_Logs" + $date1 + "_" + $time + "_.log" 
$report1 = (Get-Location).Path + "\Report" + "\" + "Report_Emchange" + $date1 + "_" + $time + "_.csv" 
 
$limit = (Get-Date).AddDays(-60) #for report recycling 
$path1 = (Get-Location).Path + "\Logs" 
$path2 = (Get-Location).Path + "\Report" 
 
$email1 = "VikasS@labtest.com" 
$from = "EmailAddressChange@labtest.com" 
$smtpserver = "smtpserver" 
 
$collmbx = @() 
$collection = @() 
$collection1 = @() 
$Statefile = ".\State-Email.csv" 
$regex = '^\d+$' 
 
################Email Function##################### 
 
function Send-Email 

    [CmdletBinding()] 
    param 
    ( 
        $From
        [array]$To
        [array]$bcc
        [array]$cc
        $body
        $subject
        $attachment
        $smtpserver 
    ) 
    $message = new-object System.Net.Mail.MailMessage 
    $message.From = $from 
    if ($To -ne $null
    { 
        $To | ForEach-Object{ 
            $to1 = $_ 
            $to1 
            $message.To.Add($to1
        } 
    } 
    if ($cc -ne $null
    { 
        $cc | ForEach-Object{ 
            $cc1 = $_ 
            $cc1 
            $message.CC.Add($cc1
        } 
    } 
    if ($bcc -ne $null
    { 
        $bcc | ForEach-Object{ 
            $bcc1 = $_ 
            $bcc1 
            $message.bcc.Add($bcc1
        } 
    } 
    $message.IsBodyHtml = $True 
    if ($subject -ne $null
    { 
        $message.Subject = $Subject 
    } 
    if ($attachment -ne $null
    { 
        $attach = new-object Net.Mail.Attachment($attachment
        $message.Attachments.Add($attach
    } 
    if ($body -ne $null
    { 
        $message.body = $body 
    } 
    $smtp = new-object Net.Mail.SmtpClient($smtpserver
    $smtp.Send($message

################################################################ 
if ($error

    Write-Host "Error in initialization"
    Send-Email -To $email1 -From $from -subject "Email Address Change Script initialization failure" -smtpserver $smtpserver 
    timeout 10; exit 

 
Start-Transcript -path $log 
get-date 
################ Collect All mailboxes########################### 
 
$collmbx = get-mailbox -resultsize unlimited | where{ $_.CustomAttribute11 -match $regex } | select Name, CustomAttribute11, PrimarySMTPAddress 
$collmbx += get-remotemailbox -resultsize unlimited | where{ $_.CustomAttribute11 -match $regex } | select Name, CustomAttribute11, PrimarySMTPAddress 
if ($error

    Write-Host "Error in Fetching mailboxes data from Exchnage"
    Send-Email -To $email1 -From $from -subject "Email Address Change error fetching mailboxes" -smtpserver $smtpserver 
    Stop-Transcript; timeout 10; exit 

If (!(Test-Path $Statefile)) 

    $collmbx | select Name, CustomAttribute11,PrimarySMTPAddress | Export-csv $Statefile -NoTypeInformation 

 
#########################Start comparison########################## 
 
$stcsv = import-csv $Statefile 
$coll = @() 
 
$Changes = Compare-Object $stcsv $collmbx -property CustomAttribute11,PrimarySMTPAddress | 
Select-Object CustomAttribute11, PrimarySMTPAddress, @{ 
    n = 'State'; e = { 
        If ($_.SideIndicator -eq "=>") { "Current" } 
        elseif ($_.SideIndicator -eq "<=") { "Previous" } 
        else { "Ignore" } 
    } 

################################################################### 
if ($changes

    $Changes | foreach-object{ 
        $mcoll = "" | select Name, CustomAttribute11, PreviousSMTP, NewSMTP 
        if ($_.state -eq "Previous"
        { 
            $cus1 = $_.CustomAttribute11 
            $Name = ($collmbx | where{$_.CustomAttribute11 -eq $cus1}).name 
            $PreviousSMTP = $_.PrimarySMTPAddress 
            foreach ($chg in $Changes
            { 
                if (($cus1 -eq $chg.CustomAttribute11) -and ($chg.state -eq "Current")) 
                { 
                    $NewSMTP = $chg.PrimarySMTPAddress 
                    $mcoll.Name = $Name 
                    $mcoll.CustomAttribute11 = $cus1 
                    $mcoll.PreviousSMTP = $PreviousSMTP 
                    $mcoll.NewSMTP = $NewSMTP 
                     
                } 
            } 
             
        } 
        $collection +$mcoll 
         
    } 
    $collection1 = $collection | where{ $_.name -ne $null } 
    if ($collection1) { $collection1$collection1 | Export-Csv $report1 -NoTypeInformation } 

 
$collmbx | Export-Csv $Statefile -NoTypeInformation # new state 
 
if($collection1){Send-Email -To $email1 -From $from -subject "Email Address Changes" -attachment $report1 -smtpserver $smtpserver
 
#################################################### 
if ($error

    Send-Email -To $email1 -From $from -subject "Email Address Change error Report" -body $Error -smtpserver $smtpserver 

 
Get-ChildItem -Path $path1 | Where-Object { 
    $_.CreationTime -lt $limit 
| Remove-Item -recurse -Force 
 
Get-ChildItem -Path $path2 | Where-Object { 
    $_.CreationTime -lt $limit 
| Remove-Item -recurse -Force 
 
get-date 
Stop-Transcript



Thanks for Reading


Sukhija Vikas

http://syscloudpro.com

 

No comments:

Post a Comment