An Azure service that is used to automate, configure, and install updates across hybrid environments.
Param(
[Parameter(Mandatory=$true)]
[string]$UPN,
[Parameter(Mandatory=$true)]
[string]$SGM_Group
)
Import module and suppress unnecessary warning text
Import-Module ExchangeOnlineManagement -WarningAction SilentlyContinue
Connect using Managed Identity
Connect-ExchangeOnline -ManagedIdentity -Organization "myorg.onmicrosoft.com"
try {
# 1. Fetch existing members safely (handling empty groups)
$ExistingMembers = Get-DistributionGroupMember -Identity $SGM_Group -ResultSize Unlimited -ErrorAction Stop |
Select-Object -ExpandProperty PrimarySmtpAddress
# 2. Check if the user is already a member (handles case-sensitivity safely)
if ($ExistingMembers -and ($ExistingMembers -contains $UPN)) {
Write-Output "$UPN already exists in $SGM_Group"
} else {
# 3. Add the user to the group
Add-DistributionGroupMember -Identity $SGM_Group -Member $UPN -BypassSecurityGroupManagerCheck -ErrorAction Stop
Write-Output "$UPN added to $SGM_Group"
}
}
catch {
Write-Error "An error occurred: $_"
}
finally {
# Always disconnect to prevent session leaks in automation
Disconnect
-ExchangeOnline -Confirm:$false
}