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 14
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.
avatar
Nicolas Coffez Jan 06, 2023
If I understand https://www.adaxes.com/info_whats-new_2023.htm correctly, it should now be possible to perform this change natively in Adaxes?
avatar
Support Jan 06, 2023
Hello Nicolas,

It is now possible to remove a user from Azure AD groups present in an Azure AD domain registered in Adaxes using native tools. At the same time, if you want to remove a user from all groups (both on-premises and Azure AD), you will still need a script. The following one should work just fine: https://www.adaxes.com/script-repository/remove-all-group-memberships-for-a-user-account-s33.htm.
avatar
Soapy Jan 31, 2023
How do we pass the user string into the email report? The report only shows what groups have been removed but doesn't state who the user is. Would be great to know which user has all their groups removed when working on multiple user accounts.
Thanks
avatar
Support Jan 31, 2023
Hello,

You can use value references (e.g. %fullname%) in the $reportHeader or $reportFooter variable. For details about value references, see https://www.adaxes.com/help/ValueReferences.
Leave a comment
Loading...

Got questions?

Support Questions & Answers