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

Iron Contributor

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. 

 

FcoManigrasso_2-1713341522721.png

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. 

 

FcoManigrasso_3-1713341586334.pngFcoManigrasso_4-1713341667409.png

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.

 

 

 

 

0 Replies