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.
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())
Any advice
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.
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.
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?
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.
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?
For the script to work, install the AzureAD PowerShell module on the computer where Adaxes service runs.
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.
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.
Thanks
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.