An Azure service that is used to automate, configure, and install updates across hybrid environments.
Define a static list of “protected” admin addresses and exclude them from the removal loop (and optionally ensure they’re always present in the group). For example:
# 1. Connect to Exchange Online (Managed Identity)
Connect-ExchangeOnline -ManagedIdentity -Organization "<domain>"
# 2. Define target Distribution Group identity
$targetGroup = "JohnsonTest2"
# 2a. Define admin addresses that must always stay in the DG
$protectedAdmins = @(
"******@contoso.com",
"******@contoso.com"
)
# 3. Import members from CSV (current class list)
$memberList = Import-Csv "C:\Test\JohnsonTest.csv"
# 4. Build a list of desired email addresses from the CSV
$desiredMembers = $memberList.UserEmail
# 5. Fetch current members (email addresses) in the DG
$existingMembers = Get-DistributionGroupMember -Identity $targetGroup |
Select-Object -ExpandProperty PrimarySmtpAddress
# 5a. Ensure protected admins are always in the group
foreach ($admin in $protectedAdmins) {
if ($existingMembers -notcontains $admin) {
try {
Add-DistributionGroupMember -Identity $targetGroup -Member $admin -ErrorAction Stop
Write-Output "Ensured protected admin ${admin} is a member of $targetGroup"
} catch {
Write-Warning "Failed to add protected admin ${admin}: $($_.Exception.Message)"
}
}
}
# 6. ADD: members that are in CSV but not yet in the group
foreach ($email in $desiredMembers) {
if ($existingMembers -contains $email) {
Write-Output "${email} is already a member of $targetGroup, skipping add."
} else {
try {
Add-DistributionGroupMember -Identity $targetGroup -Member $email -ErrorAction Stop
Write-Output "Successfully added ${email} to $targetGroup"
} catch {
Write-Warning "Failed to add ${email}: $($_.Exception.Message)"
}
}
}
# 7. REMOVE: members that are in the group but not in the CSV,
# but never remove protected admins
foreach ($email in $existingMembers) {
if ($protectedAdmins -contains $email) {
Write-Output "${email} is a protected admin, skipping removal."
continue
}
if ($desiredMembers -notcontains $email) {
try {
Remove-DistributionGroupMember -Identity $targetGroup -Member $email -Confirm:$false -ErrorAction Stop
Write-Output "Removed ${email} from $targetGroup because it is no longer in the class list."
} catch {
Write-Warning "Failed to remove ${email}: $($_.Exception.Message)"
}
}
}
Key changes:
-
$protectedAdminsholds the addresses that must never be removed. - Before removal, the script checks
if ($protectedAdmins -contains $email)and skips those members. - Optionally, step 5a ensures protected admins are always present even if they’re not in the CSV.
References: