We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script Repository

Add user to groups in Microsoft 365

May 08, 2023 Views: 7512

The scripts add a user to groups in Microsoft 365.

Parameters:

  • $groupNames - Specifies names of the groups in Microsoft 365 the user will be added to.

Distribution and mail-enabled security groups

Edit Remove
PowerShell
$groupNames = @("MyGroup1", "MyGroup2", "MyGroup3") # TODO: modify me

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 to Exchange Online
$Context.CloudServices.ConnectExchangeOnline()
    
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")
    }
}

Unified and not mail enabled security groups

For the script to work, install AzureAD PowerShell module on the computer where Adaxes service runs.

Edit Remove
PowerShell
$groupNames = @("MyGroup1", "MyGroup2", "MyGroup3") # TODO: modify me

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

try
{
    # Connect to Azure AD
    $token = $Context.CloudServices.GetAzureAuthAccessToken("https://graph.windows.net/")
    $tenant = $Context.CloudServices.GetO365Tenant()
    $credential = $tenant.GetCredential()
    Connect-AzureAD -AccountId $credential.AppId -AadAccessToken $token -TenantId $tenant.TenantId

    
    foreach ($groupName in $groupNames)
    {
        $group = Get-AzureADGroup -Filter "displayName eq '$groupName'"
        if ($NULL -eq $group)
        {
            $Context.LogMessage("Group $groupName not found", "Warning")
            continue
        }
        
        # Add user to group
        try
        {
            Add-AzureADGroupMember -ObjectId $group.ObjectID -RefObjectId $objectId.ToString() -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when adding the user to $groupName group. Error: " + $_.Exception.Message, "Warning")
        }
    }
}
finally
{
    # Disconnect from Azure AD
    Disconnect-AzureAD
}
Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers