AzureAD: list and remove group memberships (PowerShell)
List the groups of an Azure AD user or service principal and remove it from them with PowerShell.
This PowerShell script uses the AzureAD module to list the groups a user or service principal belongs to and, if needed, remove it from those groups.
Prerequisites
Install-Module AzureAD
Import-Module AzureAD
Get-Module AzureAD
Connect to the tenant:
Connect-AzureAD
Groups of a user account
$x = Get-AzureADUser -ObjectId "user@example.com"
Get-AzureADUserMembership -ObjectId $x.ObjectId | Sort-Object DisplayName | Format-Table DisplayName
Groups of a service principal
$x = Get-AzureADServicePrincipal -SearchString "sp-app-dev"
Get-AzureADServicePrincipalMembership -ObjectId $x.ObjectId | Sort-Object DisplayName | Format-Table DisplayName
$groups = Get-AzureADServicePrincipalMembership -ObjectId $x.ObjectId | Sort-Object DisplayName
Remove the service principal from its groups
A list of groups can also be supplied explicitly (for example SQL access groups named like azgr-dev-app1-sql-reader) instead of the result of Get-AzureADServicePrincipalMembership. The following loop removes the account from every group in $groups:
foreach ( $group in $groups )
{
Remove-AzureADGroupMember -ObjectId $group.ObjectId -MemberId $x.ObjectId
}
Notes
- Removal is immediate: review the content of
$groupsbefore running the loop. - The AzureAD module is deprecated by Microsoft; Microsoft Graph PowerShell is its successor.
$xmust hold a single object: check that-SearchStringreturns only one result.