Script Repository


Add user to Distribution and mail-enabled Security Groups in Microsoft 365

February 11, 2021
964

The script adds a user to Distribution and mail-enabled Security Groups in Microsoft 365.

Parameters:

  • $groupNames - Specifies names of Distribution and mail-enabled Security Groups in Microsoft 365 the user will be added to.
Edit Remove
PowerShell
$groupNames = @("MyGroup1", "MyGroup2", "MyGroup3")

try
{
    # Get the object ID in Microsoft 365
    $objectId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")
}
catch
{
    return # The user doesn't have a Microsoft 365 account
}

try
{
    $session = $Context.CloudServices.CreateExchangeOnlinePSSession()
    Import-PSSession -session $session -CommandName "Add-DistributionGroupMember"
    
    foreach ($groupName in $groupNames)
    {
        # Add user to group
        try
        {
            Add-DistributionGroupMember $groupName -Member $objectId.ToString() -BypassSecurityGroupManagerCheck -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred while adding the user to group $groupName. Error: " + $_.Exception.Message, "Warning")
        }
    }
}
finally
{
    # Close the remote session and release resources
    if ($session) { Remove-PSSession -Session $session}
}

Comments ( 0 )
No results found.
Leave a comment

Related Scripts