Email Addresses Update based on Distribution List

New requirement – New PowerShell solution 🙂

The requirement is to add additional Email addresses to the list of users in the distribution list based on below criteria:

  • User address format should match the PrimarySMTPAddress format.

Example: If primary address is Firstname.lastname@labtest.com than additional address to be added is Firstname.lastname@test.com

  • If address is already present than do noting.
  • If user primary address is changed than add the secondary address using the same logic.
  • It should work in Exchange Hybrid O365 environment

Prerequisites for Running this script:

  • Quest Active Directory Shell as it makes group member extraction easy.
  • Exchange management Shell for adding additional email addresses.

Download and extract the solution from below link

https://gallery.technet.microsoft.com/scriptcenter/Email-Addresses-Update-ff6d23a8

Update the .ps1 file.

Under variables make the following updates.

——————————————

$Dl = “GroupName”
$emaildomain = “labtest.com”
$collection1 = @()
$collection2 = @()
$count = “10” #On first run increase the count variable to a number that can accomodate all the users inside the group, after that change it to a threshold so that code can send you alert if number of updates are more than that.
$smtpserver = “smtpserver”
$from = “donotreply@lab.com”
$erroremail = “Reports@lab.com”
———————————————
Also, update your exchange CAS server under load all modules
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Exchangeserver/PowerShell/ -Authentication Kerberos

——————————————-

script will keep the log history for 60 days.

It extracts all the members recursively from the group along with their PrimarySMTPaddresses and than with split function generate the alternate required address.

$alteraddress = ($pmsmtp -split “@”)[0] + “@” + $emaildomain

It also checks if the alternate address is already present, if its already there than that user is skipped.

This is a unique environmental requirement but sharing it so that code can be reused by the community.

On first run increase the count variable to a number that can accommodate all the users inside the group, after that change it to a threshold so that code can send you alert if number of updates are more than that.

you can manually run the script by double clicking the batch file or just schedule it daily to run automatically.

PowerShell Code:

<#     
    .NOTES 
    =========================================================================== 
    Created with:     ISE 
    Created on:       01/17/2019 1:46 PM 
    Created by:       Vikas Sukhija 
    Organization:      
    Filename:         EmailAddressBasedonDls.ps1 
    =========================================================================== 
    .DESCRIPTION 
    This Script will fetch the diribution list members and add @additionaldomain address based on corporate address 
#> 
param ( 
  [string]$userlist 
) 
function Write-Log 
{ 
  [CmdletBinding()] 
  param 
  ( 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [array]$Name, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [string]$Ext, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Create')] 
    [string]$folder, 
     
    [Parameter(ParameterSetName = 'Create',Position = 0)][switch]$Create, 
     
    [Parameter(Mandatory = $true,ParameterSetName = 'Message')] 
    [String]$Message, 
    [Parameter(Mandatory = $true,ParameterSetName = 'Message')] 
    [String]$path, 
    [Parameter(Mandatory = $false,ParameterSetName = 'Message')] 
    [ValidateSet('Information','Warning','Error')] 
    [string]$Severity = 'Information', 
     
    [Parameter(ParameterSetName = 'Message',Position = 0)][Switch]$MSG 
  ) 
  switch ($PsCmdlet.ParameterSetName) { 
    "Create" 
    { 
      $log = @() 
      $date1 = Get-Date -Format d 
      $date1 = $date1.ToString().Replace("/""-") 
      $time = Get-Date -Format t 
     
      $time = $time.ToString().Replace(":""-") 
      $time = $time.ToString().Replace(" """) 
     
      foreach ($n in $Name) 
      {$log += (Get-Location).Path + "\" + $folder + "\" + $n + "_" + $date1 + "_" + $time + "_.$Ext"} 
      return $log 
    } 
    "Message" 
    { 
      $date = Get-Date 
      $concatmessage = "|$date" + "|   |" + $Message +"|  |" + "$Severity|" 
      switch($Severity){ 
        "Information"{Write-Host -Object $concatmessage -ForegroundColor Green} 
        "Warning"{Write-Host -Object $concatmessage -ForegroundColor Yellow} 
        "Error"{Write-Host -Object $concatmessage -ForegroundColor Red} 
      } 
       
      Add-Content -Path $path -Value $concatmessage 
    } 
  } 
} 
function ProgressBar 
{ 
  [CmdletBinding()] 
  param 
  ( 
    [Parameter(Mandatory = $true)] 
    $Title, 
    [Parameter(Mandatory = $true)] 
    [int]$Timer 
  ) 
     
  For ($i = 1; $i -le $Timer$i++) 
  { 
    Start-Sleep -Seconds 1; 
    Write-Progress -Activity $Title -Status "$i" -PercentComplete ($i /10 * 100) 
  } 
} 
#################Check if logs folder is created################## 
$logpath  = (Get-Location).path + "\logs"  
$testlogpath = Test-Path -Path $logpath 
if($testlogpath -eq $false) 
{ 
  ProgressBar -Title "Creating logs folder" -Timer 10 
  New-Item -Path (Get-Location).path -Name Logs -Type directory 
} 
 
##########################Load variables & Logs#################### 
$log = Write-Log -Name "log_EmailAddressUpdate" -folder logs -Ext log 
#$Report = Write-Log -Name "Report_EmailAddressUpdate" -folder Report -Ext csv 
 
$Dl = "GroupName" 
$emaildomain = "labtest.com" 
 
$collection1 = @() 
$collection2 = @() 
$count = "10" #On first run increase the count variable to a number that can accomodate all the users inside the group, after that change it to a threshold so that code can send you alert if number of updates are more than that. 
 
$smtpserver = "smtpserver" 
$from = "donotreply@lab.com" 
$erroremail = "Reports@lab.com" 
 
#########################Load all Modules#################################### 
try 
{ 
  Add-PSSnapin Quest.ActiveRoles.ADManagement 
  $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Exchangeserver/PowerShell/ -Authentication Kerberos 
  import-pssession $session -AllowClobber 
  Write-Log -Message "Script Started" -path $log -Severity Information 
  Write-Log -Message "AD and Exchange Module Loaded" -path $log -Severity Information 
} 
catch 
{ 
  Write-Host "$($_.Exception.Message)" -foregroundcolor red 
  Write-Log -Message "$($_.Exception.Message)" -path $log -Severity Error 
  Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Error - Loading AD and Exchange Module EmailAddressBasedonDls" -Body $($_.Exception.Message) 
  Exit 
} 
###################################Lets Start extracting all members############# 
$allmembers = @() 
$allmembers = Get-QADGroupMember -Identity $Dl -Indirect | select PrimarySMTPAddress 
$allmembers = $allmembers | where{$_.PrimarySMTPAddress -ne $null} 
 
 
#####################Start Checking if Emailaddress already exists############ 
 
$allmembers | ForEach-Object{ 
  $pmsmtp = $_.PrimarySMTPAddress 
  $alteraddress = ($pmsmtp -split "@")[0] + "@" + $emaildomain 
  Write-Log -Message "Userid $pmsmtp - Converted id - $alteraddress" -path $log -Severity Information 
  $checkaddress1 = get-mailbox $alteraddress -ea silentlycontinue 
  $checkaddress2 = get-remotemailbox $alteraddress -ea silentlycontinue 
  if (-not(($checkaddress1-or ($checkaddress2))) 
  { 
    Write-Log -Message "Userid $pmsmtp - Converted id - $alteraddress Check Failed" -path $log -Severity Warning 
    $onprem = get-mailbox -identity $pmsmtp -ea silentlycontinue 
    $online = get-remotemailbox -identity $pmsmtp -ea silentlycontinue 
    if($onprem){ 
      $collection1+=$pmsmtp 
      Write-Log -Message "Collected Onprem mailboxes for Processing" -path $log -Severity Information 
    } 
    if($online){ 
      $collection2+=$pmsmtp 
      Write-Log -Message "Collected Online mailboxes for Processing" -path $log -Severity Information 
    } 
  } 
  else{Write-Log -Message "Userid $pmsmtp - Converted id - $alteraddress Check Passed" -path $log -Severity Information} 
    
} 
 
#####################Start processing Email Address Update########### 
$updatecount = $collection1.count + $collection2.count 
Write-Log -Message "Total number of updates $updatecount" -path $log -Severity Information 
 
if($updatecount.count -lt $count) 
{ 
  Write-Log -Message "Start processing Email Updates for Onpremise" -path $log -Severity Information 
  if($collection1.count -gt "0"){ 
    $collection1 | ForEach-Object{ 
      $emailaddress = $_ 
      $alteremailaddress = ($emailaddress -split "@")[0] + "@" + $emaildomain 
      try 
      { 
        Set-Mailbox -identity $emailaddress -EmailAddresses @{ 
          add = $alteremailaddress 
        } 
        Write-Log -Message "Added $alteremailaddress to User $emailaddress" -path $log -Severity Information 
      } 
      catch 
      { 
        Write-Host "$($_.Exception.Message)" -foregroundcolor red 
        Write-Log -Message "$($_.Exception.Message)" -path $log -Severity Error 
      } 
    } 
  } 
  Write-Log -Message "Start processing Email Updates for Online" -path $log -Severity Information 
  if($collection2.count -gt "0"){ 
    $collection2 | ForEach-Object{ 
      $emailaddress = $_ 
      $alteremailaddress = ($emailaddress -split "@")[0] + "@" + $emaildomain 
      try 
      { 
        Set-RemoteMailbox -identity $emailaddress -EmailAddresses @{ 
          add = $alteremailaddress 
        } 
        Write-Log -Message "Added $alteremailaddress to User $emailaddress" -path $log -Severity Information 
      } 
      catch 
      { 
        Write-Host "$($_.Exception.Message)" -foregroundcolor red 
        Write-Log -Message "$($_.Exception.Message)" -path $log -Severity Error 
      } 
    } 
  } 
   
} 
else 
{ 
  Write-Log -Message "Total number of updates $updatecount are more than $count" -path $log -Severity error 
  Write-Log -Message "Script Exit" -path $log -Severity error 
  Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Error - Count of requests are more than $count - EmailAddressBasedonDls" -Body $($_.Exception.Message) 
} 
 
##############################Recycle Logs########################## 
$path2 = (Get-Location).path + "\logs"  
 
$limit = (Get-Date).AddDays(-60) #for report recycling 
Get-ChildItem -Path $path2 | 
Where-Object {$_.CreationTime -lt $limit| 
Remove-Item -recurse -Force 
 
Get-Date 
Write-Log -Message "Script Finished" -path $log -Severity Information 
Send-MailMessage -SmtpServer $smtpserver -From $from -To $erroremail -Subject "Transcript Log - EmailAddressBasedonDls" -Body "Transcript Log - EmailAddressBasedonDls" -Attachments $log 
################################################################################

 

 Thanks for downloading
 Sukhija Vikas
 http://SysCloudPro.com
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s