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

Remove user from all groups in Microsoft 365

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.
  • $skipGroups - Specifies names of the Microsoft 365 groups the user will not be removed from.
Edit Remove
PowerShell
$skipGroups = @("Group1", "Group2") # TODO: modify me

# 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"
    
    # 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 "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)
        if ($skipGroups -contains $group.DisplayName)
        {
            continue
        }
        
        try
        {
            # Remove the user from group
            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 ($skipGroups -contains $group.DisplayName)
        {
            continue
        }
        
        if ($passedGroupIDs.Contains($group.ObjectId))
        {
            continue
        }
        
        try
        {
            # Remove the user from group
            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 10
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
David Nov 24, 2022
Hello, Are there any updates to this error? Thanks,
avatar
Support Nov 25, 2022
Hello David,

As per our check there are no updates. The error comes from Microsoft 365 and you can only retry it. As an option, you can try using the MgGraph module instead of the AzureAD one. For an example of the module usage, see https://www.adaxes.com/sdk/CloudServicesScriptContextClass/#examples-2.
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.
avatar
Jeff Roncone Mar 16, 2022
Is there a way to list the groups that user was remove from to a text file instead of an email ?
avatar
Support Mar 17, 2022
Hello Jeff,

Yes, it is possible. For us to update the script for you, please, provide us with an example of the resulting file you need. You can email it at support@adaxes.com.
Leave a comment
Loading...

Got questions?

Support Questions & Answers