Forum Discussion

FcoManigrasso's avatar
FcoManigrasso
Iron Contributor
Apr 17, 2024

Script to rename Distribution groups and change PrimarySMTPAddress in order to keep them as backup

Hello team,

 

Recently I faced a scenario where I needed to recreate several Distribution Groups, (hundreds), avoiding deleting the previous ones to keep them as rollback plan. 

As you know, if we want to keep the previous ones, we need to change the name, alias ecc in order to have those available for the new ones. So, I prepared this script for the task and share it here as maybe can be useful for some of you.

 

What do you need? 

 

A single column csv file, with "name" as header, and listed all the DGs addresses. 

 

The script will go through all of them, adding "OLD_" in front of the name, displayname and alias. It will also add the modified alias as the PrimarySMTPAddress and will remove the previous one. 

 

Find the script below. 

NOTE: Remember to edit your csv file path and file name, the domain for your desired addresses and the prefix for your renamed groups. (If you don´t want to use "OLD_" you can simply change that for something that you prefer).

 

# Connect to Exchange Online
Connect-ExchangeOnline

# Import CSV file
$csvPath = "C:\temp\RenameDLs10042024.csv"
$groups = Import-Csv -Path $csvPath

foreach ($group in $groups) {
    $groupName = $group.Name

    # Get the distribution group
    $distributionGroup = Get-DistributionGroup -Identity $groupName

    if ($distributionGroup) {
        # Modify the properties
        $newName = "OLD_" + $distributionGroup.Name
        $newDisplayName = "OLD_" + $distributionGroup.DisplayName
        $newAlias = "OLD_" + $distributionGroup.Alias

        Set-DistributionGroup -Identity $groupName -Name $newName -DisplayName $newDisplayName -Alias $newAlias

        # Set the new alias as primary SMTP address
        Set-DistributionGroup -Identity $newName -PrimarySmtpAddress "$email address removed for privacy reasons"

        # Delete the previous primary SMTP address
        $primarySMTP = $distributionGroup.PrimarySmtpAddress
        Set-DistributionGroup -Identity $newName -EmailAddresses @{Remove="$primarySMTP"}

        Write-Host "Distribution group '$groupName' updated with new properties."
    } else {
        Write-Host "Distribution group '$groupName' not found."
    }
}

 

As usual, even if I tested it and works well for me, please test it first of running it in your PROD environment.

 

Cheers.

 

 

 

 

No RepliesBe the first to reply

Resources