Script Repository


Remove user from all groups in Microsoft 365

September 27, 2021
2690

The script removes a user from all groups in Microsoft 365 (Office 365) and sends a list of the groups to an email address. You can use the script in business rules, custom commands and scheduled tasks configured for the User object type.

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

Parameters:

  • $to - Specifies the recipient email address.
  • $subject - Specifies the email notification subject.
  • $reportHeader - Specifies the report header.
  • $reportFooter - Specifies the report footer.
Edit Remove
PowerShell
# E-mail settings
$to = "recipient@domain.com" # TODO: modify me
$subject = "Groups report" # TODO: modify me
$reportHeader = "<h2>The user has been removed from the following groups:</h2>" # TODO: modify me
$reportFooter = "<hr /><p><i>Please do not reply to this e-mail, it has been sent to you for notification purposes only.</i></p>" # TODO: modify me

# Get the user's unique identifier in Microsoft 365
try
{
    $objectId = ([Guid]$Context.TargetObject.Get("adm-O365ObjectId")).ToString()
}
catch
{
    $Context.LogMessage("The user doesn't have an account in Microsoft 365", "Warning")
    return
}

try
{
    # Connect to Exchange Online
    $session = $Context.CloudServices.CreateExchangeOnlinePSSession()
    Import-PSSession $session -AllowClobber -DisableNameChecking -CommandName "Get-User", "Get-Recipient", "Remove-DistributionGroupMember", "Remove-UnifiedGroupLinks"
    
    # 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
    
    # Get user DN
    $user = Get-User $objectId
    $userDN = $user.DistinguishedName
    
    # Get all groups in Exchange Online the user is member of
    $groups = Get-Recipient -Filter "Members -eq '$userDN'" -RecipientTypeDetails "GroupMailbox","MailUniversalDistributionGroup","MailUniversalSecurityGroup"
    $groupList = New-Object "System.Text.StringBuilder"
    $passedGroupIDs = New-Object "System.Collections.Generic.HashSet[System.String]"
    foreach ($group in $groups)
    {
        $passedGroupIDs.Add($group.ExternalDirectoryObjectId)
        try
        {
            # Remove the user
            if ($group.RecipientTypeDetails -eq "GroupMailbox")
            {
                Remove-UnifiedGroupLinks -Identity $group.ExternalDirectoryObjectId -LinkType Members -Links $objectID -Confirm:$False -ErrorAction Stop
            }
            else
            {
                Remove-DistributionGroupMember $group.ExternalDirectoryObjectId -Member $objectId -Confirm:$False -ErrorAction Stop -BypassSecurityGroupManagerCheck
            }
        }
        catch
        {
            $Context.LogMessage("Cannot remove the user from group $($group.DisplayName). Error message: " + $_.Exception.Message, "Warning")
            continue
        }
        
        [void]$groupList.Append("<li>" + $group.DisplayName + "</li>")
    }
    
    # Get all groups in Microsoft 365 the user is member of
    $groups = Get-AzureADUserMembership -ObjectId $objectId -All:$True
    foreach ($group in $groups)
    {
        if ($passedGroupIDs.Contains($group.ObjectId))
        {
            continue
        }
        
        try
        {
            # Remove the user
            Remove-AzureADGroupMember -ObjectId $group.ObjectId -MemberId $objectId -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("Cannot remove the user from group $($group.DisplayName). Error message: " + $_.Exception.Message, "Warning")
            continue
        }
        
        [void]$groupList.Append("<li>" + $group.DisplayName + "</li>")
    }
    
}
finally
{
    # Close the remote session and release resources
    if ($session) { Remove-PSSession $session }
    Disconnect-AzureAD
}

if ($groupList.Length -eq 0)
{
    return
}

# Build report
$html = New-Object "System.Text.StringBuilder"
[void]$html.Append($reportHeader)
[void]$html.Append("<ul>")
[void]$html.Append($groupList.ToString())
[void]$html.Append("</ul>")
[void]$html.Append($reportFooter)

# Send mail
$Context.SendMail($to, $subject, $NULL, $html.ToString())

Comments ( 6 )
avatar
Dustin Anderson
May 06, 2021
Getting "Cannot remove user from group "GROUP NAME". Error message: We failed to update the group mailbox. Please try again later.

Any advice
avatar
Support
May 06, 2021
Hello Dustin,

Such errors sometimes occur and there is no actual cause for them that might be fixed. Unfortunately, all you can do is try again later as the error message states.
avatar
Allili Omar
Aug 10, 2021
Hello,

Unfortunately it's not working, with the following error message:
Cannot validate argument on parameter 'AccountId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. Stack trace: at <ScriptBlock>, <No file>

Could anyone please assist?
avatar
Support
Aug 10, 2021
Hello Omar,

It looks like your Microsoft 365 tenant is registered in Adaxes with the credentials of a user account while the script requires it to be done with an application account. For details on how to register your Microsoft 365 tenant with an application account, have a look at the following help article: https://www.adaxes.com/help/RegisterAdaxesAsAppMicrosoftAzure. The feature is available only starting with Adaxes 2021.1. For information on how to check your current Adaxes version, seehttps://www.adaxes.com/help/CheckServiceVersion.
avatar
Jack LaQuatra
Sep 27, 2021
Hello - we are getting the following errors with this script:
The term 'Disconnect-AzureAD' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Stack trace: at <ScriptBlock>, <No file>: line 91
The term 'Connect-AzureAD' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. Stack trace: at <ScriptBlock>, <No file>: line 29

Anyone know how to resolve this?
avatar
Support
Sep 27, 2021
Hello Jack,

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