Script Repository


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

June 19, 2020
515

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

To use the script, install the EXO V2 PowerShell module on the computer where Adaxes service runs.

Parameters:

  • $groupNames - Specifies names of Distribution and mail-enabled Security Groups in Microsoft 365 the user will be added to.
Edit Remove
PowerShell
Import-Module ExchangeOnlineManagement

$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
}

Connect-ExchangeOnline -Credential $Context.GetOffice365Credential()

foreach ($groupName in $groupNames)
{
    # Add user to group
    try
    {
        Add-DistributionGroupMember $groupName -Member $objectId.ToString() -BypassSecurityGroupManagerCheck -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred when adding the user to $groupName group. Error: " + $_.Exception.Message, "Warning")
    }
}

Comments ( 0 )
No results found.
Leave a comment

Related Scripts