Script Repository


Add user to groups in Microsoft 365

April 07, 2021
1262

The script adds 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")

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

Unified and not mail enabled security groups

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 -SearchString $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
{
    # Disconnest from Azure AD
	Disconnect-AzureAD
}

Comments ( 0 )
No results found.
Leave a comment

Related Scripts