Skip to content

Add Users to Multiple Groups - DL,M365 or Mail-Enabled SG

Updated: at 06:30 PM

If you find yourself having to manually include a user in various groups, whether they are Microsoft 365, Distribution Lists, or mail-enabled security groups, this script can be quite handy. However, my initial suggestion would be to leverage dynamic rules for group assignments. Dynamic groups automatically include users based on predefined criteria. For instance:

Users Deparmtent is Human Resource -> User is added to SG-HR

Utilizing dynamic groups can significantly improve your user group assignments, making the process more efficient and easil scalable.

PowerShell Script

# Specify the path to your CSV file
$csvPath = "C:\csvexport\addtogroups.csv"

# Connect to Exchange Online
Connect-ExchangeOnline

# Import CSV
$csvData = Import-Csv -Path $csvPath

# Loop through each row in the CSV
foreach ($row in $csvData) {
    $user = $row.User
    $groupName = $row.GroupName

    # Check if the group is a Distribution Group
    if (Get-DistributionGroup -Identity $groupName -ErrorAction SilentlyContinue) {
        try {
            Add-DistributionGroupMember -Identity $groupName -Member $user -ErrorAction Stop
            Write-Host -ForegroundColor Green "Added user '$user' to Distribution Group '$groupName'"
        }
        catch {
            Write-Host -ForegroundColor Red "Failed to add user '$user' to Distribution Group '$groupName'. Error: $_"
        }
    }
    # Check if the group is a Microsoft 365 Group
    elseif (Get-UnifiedGroup -Identity $groupName -ErrorAction SilentlyContinue) {
        try {
            Add-UnifiedGroupLinks -Identity $groupName -LinkType Members -Links $user -ErrorAction Stop
            Write-Host -ForegroundColor Green "Added user '$user' to Microsoft 365 Group '$groupName'"
        }
        catch {
            Write-Host -ForegroundColor Red "Failed to add user '$user' to Microsoft 365 Group '$groupName'. Error: $_"
        }
    }
    else {
        Write-Host -ForegroundColor Yellow "Group '$groupName' not recognized as a Distribution Group or Microsoft 365 Group."
    }
}

# Disconnect from Exchange Online
Disconnect-ExchangeOnline -Confirm:$false

✨ Feedback & Suggestions

If you have any suggestions/feedback, you can contact me via my email.