The Remove-MgDirectoryRoleMemberByRef cmdlet is used to remove a user, group, or service principal from a directory role in Microsoft Entra ID (Azure AD) using Microsoft Graph PowerShell. This is essential for automating administrative deprovisioning tasks or role reassignment workflows.
Remove-MgDirectoryRoleMemberByRef -DirectoryRoleId <String> -DirectoryObjectId <String>
$roleId = (Get-MgDirectoryRole -Filter "displayName eq 'Company Administrator'").Id
$userId = (Get-MgUser -UserId "alex.williams@contoso.com").Id
Remove-MgDirectoryRoleMemberByRef -DirectoryRoleId $roleId -DirectoryObjectId $userId
This script removes Alex Williams from the Global Administrator role.
$customRole = Get-MgDirectoryRole -Filter "displayName eq 'App Manager'"
$sp = Get-MgServicePrincipal -Filter "displayName eq 'CustomApp1'"
Remove-MgDirectoryRoleMemberByRef -DirectoryRoleId $customRole.Id -DirectoryObjectId $sp.Id
This removes the CustomApp1 service principal from the App Manager role.
$roleId = (Get-MgDirectoryRole -Filter "displayName eq 'User Administrator'").Id
$groupId = (Get-MgGroup -Filter "displayName eq 'HR Admins'").Id
Remove-MgDirectoryRoleMemberByRef -DirectoryRoleId $roleId -DirectoryObjectId $groupId
This command removes HR Admins group from the User Administrator directory role.
Scenario | Description |
User Offboarding | Automatically remove a departing employee from all directory roles. |
Role Reassignment | Shift responsibilities by removing old members before assigning new ones. |
Audit & Compliance | Ensure only authorized identities remain in high-privilege roles. |
App Access Revocation | Detach service principals from privileged roles when no longer required. |
Error | Cause | Solution |
Authorization_RequestDenied | Insufficient permissions | Ensure the signed-in account has RoleManagement.ReadWrite.Directory permission. |
ResourceNotFound | Incorrect or missing DirectoryRoleId or DirectoryObjectId | Double-check both values using Get-MgDirectoryRole and Get-MgUser/Get-MgGroup/Get-MgServicePrincipal. |
Access Denied | Directory role doesn't exist or user is not a member | Validate that the identity is indeed a member of the specified role. Use Get-MgDirectoryRoleMember. |
The Remove-MgDirectoryRoleMemberByRef cmdlet is a powerful tool for securely managing role memberships in Microsoft Entra ID. By integrating it into your automation or compliance scripts, you can ensure timely deprovisioning of privileged access and maintain a secure administrative boundary.
Use it responsibly in conjunction with Get-MgDirectoryRole and Get-MgDirectoryRoleMember to maintain visibility and control over role assignments in your tenant
© m365corner.com. All Rights Reserved. Design by HTML Codex