An Azure service that is used to automate, configure, and install updates across hybrid environments.
Hello Tyler Johnson, we understand that you're Azure Automation Runbook that adds members to an Exchange Online Distribution Group, and the script fails when a person from your input list is already a member of the group. You want the runbook to skip existing members and only add new ones, so it doesn’t error out on duplicates.
Your runbook fails because Add-DistributionGroupMember throws an error when you try to add a member who is already present in the distribution group. If you don’t handle that condition (by checking first or handling the error), the runbook treats it as a terminating failure and stops. The “check existing members and skip” logic avoids triggering that error path.
You can try with the below script that can validate the existing member and skip the member that already exist.
#1. Connect to Exchange Online (Use Managed Identity for Azure Automation)
Connect-ExchangeOnline -ManagedIdentity -Organization "
#2. Define target Distribution Group identity
Get-DistributionGroup -Identity "JohnsonTest2"
#3. Import members from a CSV file
$memberList = Import-Csv "C:\Test\JohnsonTest.csv"
#4. Fetch current members (Email addresses) to compare against
$targetGroup = "JohnsonTest2"
$existingMembers = Get-DistributionGroupMember -Identity $targetGroup | Select-Object -ExpandProperty PrimarySmtpAddress
#5. Loop through the list and add members
foreach ($row in $memberList) {
if ($existingMembers -contains $row.UserEmail) {
Write-Output "$($row.UserEmail) is already a member of $targetGroup, skipping."
} else {
try {
Add-DistributionGroupMember -Identity $targetGroup -Member $row.UserEmail -ErrorAction Stop
Write-Output "Successfully added $($row.UserEmail) to $targetGroup"
} catch {
Write-Warning "Failed to add $($row.UserEmail): $($_.Exception.Message)"
}
}
}
Hope this helps. and please feel free to reach out if you have any further questions. Thanks