Skip to main content

Scoped Custom Role for Security Group Sync

Administrator

This tutorial sets up Option A from the Security Group Sync Service Principal guide. You run one PowerShell script that lets the DataCentral service principal read the security groups you choose and add or remove their members. It cannot touch any other group.


What the script creates​

ObjectDefault namePurpose
Custom roleGroup Membership Manager (scoped)Grants only groups/members/update, groups/members/read and groups/standard/read.
Administrative unit (AU)Groups managed by automationThe boundary. Holds only the groups you name.
Role assignmentService principal at AU scopeBinds the role to the service principal inside that boundary only.

The script does not create the app registration or the security groups. Both must already exist. Create the app registration as described in Register an Application in Entra ID.

How DataCentral uses this access​

An Organizational Unit (OU) in DataCentral can be linked to one of your Entra ID security groups. DataCentral then uses the service principal only for that linked group.

WhenWhat DataCentral does in Entra ID
An admin links an OU to a security groupReads the group's ID and name, to confirm the group exists and name the OU.
An admin selects Preview comparison or Entra ID syncReads the group's members and their name and email, and creates matching DataCentral users. This only reads from Entra ID.
An admin adds a user to a linked OU in DataCentralAdds that user to the linked security group.
An admin removes a user from a linked OU in DataCentralRemoves that user from the linked security group.

Every change in Entra ID follows an action by a DataCentral administrator. DataCentral runs no scheduled jobs that change your groups.

DataCentral never:

  • creates, renames or deletes groups, or changes group owners or settings
  • reads or changes groups outside the administrative unit
  • changes any user account or user property
  • searches or browses your directory. It only reads users who are members of a linked group.

What DataCentral stores: the linked group's object ID and name, and for each member the Entra object ID, display name and email address. DataCentral uses these to create and match DataCentral user accounts.

Prerequisites​

RequirementDetail
LicenceMicrosoft Entra ID P1 or higher. Custom roles and AU-scoped role assignments depend on it.
Your accountPrivileged Role Administrator or Global Administrator. The script creates a role definition, an administrative unit and a role assignment.
PowerShellPowerShell 7 recommended. Windows PowerShell 5.1 also works with the Graph SDK.
Group namesExact display name of each security group. Each name must match one group.
Service principalA single-tenant app registration you created for DataCentral, with a client secret. You pass its Application (client) ID, found under App registrations or Enterprise applications. Use a dedicated app registration for this, not one shared with other systems.

Groups the script accepts​

The script validates every group before it changes anything and stops with a clear error if a group does not qualify.

  • The group must be a security group.
  • It must not be role-assignable. Only Global Administrators and Privileged Role Administrators can change membership of those groups.
  • It must not be dynamic. Dynamic membership rules control members.
  • It must not be synced from on-premises AD. Manage those members on-premises.

Script parameters​

ParameterDefaultDescription
-GroupNamesRequiredOne or more security group display names, separated by commas.
-ServicePrincipalClientIdRequiredApplication (client) ID of the existing service principal. Must be a GUID.
-AdminUnitNameGroups managed by automationAU that holds the managed groups. Created if missing.
-CustomRoleNameGroup Membership Manager (scoped)Custom role name. Created if missing.
-WhatIfOffPreview without changing anything.

Step 1: Install the Microsoft Graph PowerShell modules​

Install the full SDK, or only the five modules the script calls. The full SDK is large. The targeted install is faster.

# Option A: full SDK
Install-Module Microsoft.Graph -Scope CurrentUser

# Option B: only the modules this script uses
Install-Module Microsoft.Graph.Authentication,
Microsoft.Graph.Applications,
Microsoft.Graph.Groups,
Microsoft.Graph.Identity.DirectoryManagement,
Microsoft.Graph.Identity.Governance -Scope CurrentUser

Confirm the install:

Get-Module Microsoft.Graph* -ListAvailable | Select-Object Name, Version

Step 2: Save the scripts​

Save both scripts to a working folder, for example C:\Scripts.

ScriptUse it to
Grant-GroupMembershipManagement.ps1Create the custom role and the administrative unit, add the groups, and assign the role. Prints progress and verification hints.
Add-GroupToAdministrativeUnit.ps1Add more groups to the existing AU later. See Add more groups later.
<#
.SYNOPSIS
Lets a service principal add/remove members of specific security groups in Entra ID,
without letting it rename, edit, delete or own those groups.

.DESCRIPTION
1. Creates (or reuses) a custom role that can only read groups and add or remove their members.
2. Creates (or reuses) an administrative unit (AU) and adds the specified groups to it.
3. Assigns the custom role to the service principal, scoped to that AU only.

Re-running the script is safe: existing objects are reused, not duplicated.

.PARAMETER GroupNames
Display name(s) of the security group(s) the service principal may manage.

.PARAMETER ServicePrincipalClientId
Application (client) ID of the service principal.

.PARAMETER AdminUnitName
AU that will hold the managed groups. Created if it does not exist.

.PARAMETER CustomRoleName
Name of the custom role. Created if it does not exist.

.EXAMPLE
.\Grant-GroupMembershipManagement.ps1 -GroupNames "SG-App-Users" -ServicePrincipalClientId "11111111-2222-3333-4444-555555555555" -WhatIf

.EXAMPLE
.\Grant-GroupMembershipManagement.ps1 -GroupNames "SG-App-Users","SG-App-Admins" -ServicePrincipalClientId "11111111-2222-3333-4444-555555555555"

.NOTES
Requirements:
- Microsoft Graph PowerShell SDK: Install-Module Microsoft.Graph -Scope CurrentUser
- Entra ID P1 (custom roles and AU-scoped role assignments)
- The signed-in admin needs Privileged Role Administrator (or Global Administrator).

Limitations:
- Role-assignable groups cannot be managed via AU-scoped custom roles.
- Dynamic and on-premises synced groups cannot have members edited manually.
- Whether the service principal's app-only Graph calls also need a Graph application
permission (e.g. GroupMember.ReadWrite.All) depends on how it authenticates. Such a
permission is tenant-wide and would bypass the AU scoping, so test carefully
(see the verification hints printed at the end).
- The custom role does not cover the member users themselves, since they are not in the AU.
To read members' displayName and mail, grant the app the Graph application permission
User.ReadBasic.All (tenant-wide, read-only) and grant admin consent.
#>

[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[string[]]$GroupNames,

[Parameter(Mandatory = $true)]
[guid]$ServicePrincipalClientId,

[string]$AdminUnitName = 'Groups managed by automation',

[string]$CustomRoleName = 'Group Membership Manager (scoped)'
)

$ErrorActionPreference = 'Stop'

function Escape-ODataString([string]$Value) {
return $Value -replace "'", "''"
}

# ---------------------------------------------------------------------------
# Connect
# ---------------------------------------------------------------------------
$requiredScopes = @(
'RoleManagement.ReadWrite.Directory',
'AdministrativeUnit.ReadWrite.All',
'Group.Read.All',
'Application.Read.All'
)

Write-Host 'Connecting to Microsoft Graph...' -ForegroundColor Cyan
Connect-MgGraph -Scopes $requiredScopes -NoWelcome

# ---------------------------------------------------------------------------
# Resolve service principal
# ---------------------------------------------------------------------------
Write-Host "Resolving service principal with client ID '$ServicePrincipalClientId'..." -ForegroundColor Cyan

$sp = Get-MgServicePrincipal -Filter "appId eq '$ServicePrincipalClientId'"
if (-not $sp) { throw "No service principal with client ID '$ServicePrincipalClientId' was found in this tenant." }
Write-Host " Found: $($sp.DisplayName) (ObjectId: $($sp.Id), AppId: $($sp.AppId))" -ForegroundColor Green

# ---------------------------------------------------------------------------
# Resolve and validate groups
# ---------------------------------------------------------------------------
Write-Host 'Resolving groups...' -ForegroundColor Cyan

$groups = foreach ($name in $GroupNames) {
$matches = @(Get-MgGroup -Filter "displayName eq '$(Escape-ODataString $name)'" `
-Property 'id,displayName,securityEnabled,groupTypes,isAssignableToRole,membershipRule,onPremisesSyncEnabled' -All)

if ($matches.Count -eq 0) { throw "Group '$name' was not found." }
if ($matches.Count -gt 1) {
throw "Multiple groups are named '$name'. Rename one or adapt the script to use object IDs."
}

$g = $matches[0]

if (-not $g.SecurityEnabled) {
throw "Group '$name' is not a security group."
}
if ($g.IsAssignableToRole) {
throw "Group '$name' is role-assignable. Its membership cannot be managed with an AU-scoped custom role."
}
if ($g.GroupTypes -contains 'DynamicMembership' -or $g.MembershipRule) {
throw "Group '$name' is a dynamic group. Members cannot be added or removed manually."
}
if ($g.OnPremisesSyncEnabled) {
throw "Group '$name' is synced from on-premises AD. Members must be managed on-premises."
}

Write-Host " OK: $($g.DisplayName) ($($g.Id))" -ForegroundColor Green
$g
}

# ---------------------------------------------------------------------------
# Custom role (membership only: no rename, no delete, no ownership changes)
# ---------------------------------------------------------------------------
Write-Host "Checking custom role '$CustomRoleName'..." -ForegroundColor Cyan

# standard/read is needed so the service principal can read group properties such as displayName
$requiredRoleActions = @(
'microsoft.directory/groups/members/update',
'microsoft.directory/groups/members/read',
'microsoft.directory/groups/standard/read'
)

$role = Get-MgRoleManagementDirectoryRoleDefinition -Filter "displayName eq '$(Escape-ODataString $CustomRoleName)'" |
Select-Object -First 1

if ($role) {
Write-Host " Role already exists (Id: $($role.Id)). Reusing it." -ForegroundColor Yellow
$allowed = $role.RolePermissions.AllowedResourceActions
$unexpected = $allowed | Where-Object { $_ -notin $requiredRoleActions }
if ($unexpected) {
Write-Warning "The existing role contains extra permissions: $($unexpected -join ', '). Review before relying on it."
}
}
elseif ($PSCmdlet.ShouldProcess($CustomRoleName, 'Create custom role')) {
$roleParams = @{
DisplayName = $CustomRoleName
Description = 'Can read groups in scope and add or remove their members. Cannot edit, rename, delete or change owners.'
IsEnabled = $true
RolePermissions = @(
@{
AllowedResourceActions = $requiredRoleActions
}
)
}
$role = New-MgRoleManagementDirectoryRoleDefinition -BodyParameter $roleParams
Write-Host " Created role (Id: $($role.Id))." -ForegroundColor Green
}

# ---------------------------------------------------------------------------
# Administrative unit
# ---------------------------------------------------------------------------
Write-Host "Checking administrative unit '$AdminUnitName'..." -ForegroundColor Cyan

$au = Get-MgDirectoryAdministrativeUnit -Filter "displayName eq '$(Escape-ODataString $AdminUnitName)'" |
Select-Object -First 1

if ($au) {
Write-Host " AU already exists (Id: $($au.Id)). Reusing it." -ForegroundColor Yellow
}
elseif ($PSCmdlet.ShouldProcess($AdminUnitName, 'Create administrative unit')) {
$au = New-MgDirectoryAdministrativeUnit -BodyParameter @{
displayName = $AdminUnitName
description = 'Groups whose membership is managed by an automation service principal.'
}
Write-Host " Created AU (Id: $($au.Id))." -ForegroundColor Green
}

# ---------------------------------------------------------------------------
# Add groups to the AU
# ---------------------------------------------------------------------------
if ($au) {
$existingMemberIds = @(Get-MgDirectoryAdministrativeUnitMember -AdministrativeUnitId $au.Id -All | ForEach-Object { $_.Id })

foreach ($g in $groups) {
if ($existingMemberIds -contains $g.Id) {
Write-Host " Group '$($g.DisplayName)' is already in the AU." -ForegroundColor Yellow
continue
}
if ($PSCmdlet.ShouldProcess($g.DisplayName, "Add to administrative unit '$AdminUnitName'")) {
New-MgDirectoryAdministrativeUnitMemberByRef -AdministrativeUnitId $au.Id -BodyParameter @{
'@odata.id' = "https://graph.microsoft.com/v1.0/groups/$($g.Id)"
}
Write-Host " Added '$($g.DisplayName)' to the AU." -ForegroundColor Green
}
}
}

# ---------------------------------------------------------------------------
# Assign the role to the service principal, scoped to the AU
# ---------------------------------------------------------------------------
if ($role -and $au) {
$scope = "/administrativeUnits/$($au.Id)"
Write-Host 'Checking role assignment...' -ForegroundColor Cyan

$existingAssignment = Get-MgRoleManagementDirectoryRoleAssignment `
-Filter "principalId eq '$($sp.Id)' and roleDefinitionId eq '$($role.Id)'" -All |
Where-Object { $_.DirectoryScopeId -eq $scope } |
Select-Object -First 1

if ($existingAssignment) {
Write-Host ' Assignment already exists.' -ForegroundColor Yellow
}
elseif ($PSCmdlet.ShouldProcess($sp.DisplayName, "Assign '$CustomRoleName' scoped to AU '$AdminUnitName'")) {
$null = New-MgRoleManagementDirectoryRoleAssignment -BodyParameter @{
principalId = $sp.Id
roleDefinitionId = $role.Id
directoryScopeId = $scope
}
Write-Host " Assigned '$CustomRoleName' to '$($sp.DisplayName)' at scope $scope." -ForegroundColor Green
}
}

# ---------------------------------------------------------------------------
# Summary and verification hints
# ---------------------------------------------------------------------------
Write-Host ''
Write-Host 'Done.' -ForegroundColor Cyan
Write-Host @"

Verify with the service principal's own token:
- Add/remove a member in a group inside the AU -> should succeed
- Add/remove a member in a group outside the AU -> should fail (403)
- PATCH a group's displayName, or DELETE the group -> should fail (403)

If the app-only call is rejected even for groups inside the AU, it may also need a Graph
application permission. Granting GroupMember.ReadWrite.All is tenant-wide and can override
the AU scoping, so re-test the 'outside the AU' case after any such change.
"@
<#
.SYNOPSIS
Adds security groups to an existing administrative unit, so the service principal that
holds the AU-scoped custom role can manage their members.

.PARAMETER GroupNames
Display name(s) of the security group(s) to add.

.PARAMETER AdminUnitName
Name of the existing administrative unit.

.EXAMPLE
.\Add-GroupToAdministrativeUnit.ps1 -GroupNames "SG-App-Users","SG-App-Admins" -WhatIf
#>

[CmdletBinding(SupportsShouldProcess = $true)]
param(
[Parameter(Mandatory = $true)]
[string[]]$GroupNames,

[string]$AdminUnitName = 'Groups managed by automation'
)

$ErrorActionPreference = 'Stop'

function Escape-ODataString([string]$Value) {
return $Value -replace "'", "''"
}

Connect-MgGraph -Scopes 'AdministrativeUnit.ReadWrite.All', 'Group.Read.All' -NoWelcome

$au = Get-MgDirectoryAdministrativeUnit -Filter "displayName eq '$(Escape-ODataString $AdminUnitName)'" |
Select-Object -First 1
if (-not $au) { throw "Administrative unit '$AdminUnitName' was not found. Run Grant-GroupMembershipManagement.ps1 first." }

$groups = foreach ($name in $GroupNames) {
$matches = @(Get-MgGroup -Filter "displayName eq '$(Escape-ODataString $name)'" `
-Property 'id,displayName,securityEnabled,groupTypes,isAssignableToRole,membershipRule,onPremisesSyncEnabled' -All)

if ($matches.Count -eq 0) { throw "Group '$name' was not found." }
if ($matches.Count -gt 1) { throw "Multiple groups are named '$name'." }

$g = $matches[0]

if (-not $g.SecurityEnabled) { throw "Group '$name' is not a security group." }
if ($g.IsAssignableToRole) { throw "Group '$name' is role-assignable and cannot be managed with an AU-scoped custom role." }
if ($g.GroupTypes -contains 'DynamicMembership' -or $g.MembershipRule) { throw "Group '$name' is a dynamic group." }
if ($g.OnPremisesSyncEnabled) { throw "Group '$name' is synced from on-premises AD." }

$g
}

$existingMemberIds = @(Get-MgDirectoryAdministrativeUnitMember -AdministrativeUnitId $au.Id -All | ForEach-Object { $_.Id })

foreach ($g in $groups) {
if ($existingMemberIds -contains $g.Id) {
Write-Host "Already in AU: $($g.DisplayName)" -ForegroundColor Yellow
continue
}
if ($PSCmdlet.ShouldProcess($g.DisplayName, "Add to administrative unit '$AdminUnitName'")) {
New-MgDirectoryAdministrativeUnitMemberByRef -AdministrativeUnitId $au.Id -BodyParameter @{
'@odata.id' = "https://graph.microsoft.com/v1.0/groups/$($g.Id)"
}
Write-Host "Added to AU: $($g.DisplayName)" -ForegroundColor Green
}
}

Files saved from a browser or email carry a block flag, so clear it. If your execution policy still blocks the scripts, relax it for the current session only. The change disappears when you close the window.

cd C:\Scripts
Get-ChildItem *.ps1 | Unblock-File

# Only if the execution policy blocks the script
Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned

Step 3: Preview the changes with -WhatIf​

Run the script with -WhatIf first. It signs in, resolves your service principal, validates the groups, and reports what it would create. It changes nothing in the tenant.

.\Grant-GroupMembershipManagement.ps1 `
-GroupNames "SG-App-Users" `
-ServicePrincipalClientId "11111111-2222-3333-4444-555555555555" `
-WhatIf
What to expect on a first run

The preview reports the role and administrative unit creation only. Adding groups and assigning the role depend on objects that do not exist yet, so the script skips those steps in preview mode. Resolution and validation errors still appear, which is the point of this step.

What a clean preview does not prove

-WhatIf does not test whether your account may create roles and assignments, or whether the tenant has the required licence. Those surface only on a real run.

Step 4: Run the script​

Remove -WhatIf to apply the configuration. Pass several groups as a comma-separated list. A space without a comma fails with A positional parameter cannot be found.

.\Grant-GroupMembershipManagement.ps1 `
-GroupNames "SG-App-Users","SG-App-Admins" `
-ServicePrincipalClientId "11111111-2222-3333-4444-555555555555"

A browser window opens for sign-in. Sign in with the account that holds the required admin role and approve these delegated permissions. An administrator may need to grant consent.

PermissionUsed for
RoleManagement.ReadWrite.DirectoryCreate the custom role and the assignment
AdministrativeUnit.ReadWrite.AllCreate the AU and add groups to it
Group.Read.AllFind and validate the groups
Application.Read.AllFind the service principal

The script prints a green line for each object it creates and a yellow line for each one that already exists. Re-running it is safe, because it reuses existing objects.

If the custom role already exists

The script reuses a role with the same name as is and does not add missing actions. If the role lacks groups/standard/read, add it under Roles & admins > Roles & admins > your custom role > Description > Edit > Permissions.

Step 5: Grant User.ReadBasic.All to the app​

If you already added User.ReadBasic.All as described in Configure API Permissions, skip to Step 6.

Why DataCentral needs this permission​

When DataCentral reads a linked group's members, Entra ID returns each member's object ID. To show who the members are and to create a DataCentral account for each of them, DataCentral needs each member's display name and email address.

The custom role cannot grant this. It covers the groups in the AU, but not the users who are members of those groups, because users are not in the AU. Entra ID has no permission that limits user reads to members of specific groups, so User.ReadBasic.All is the narrowest permission that works. Without it, DataCentral sees members as object IDs only, with an empty displayName and mail, and cannot create their DataCentral accounts.

What it allows and what it does not:

  • It is read-only. DataCentral cannot change any user with it.
  • It exposes only the basic profile: display name, first and last name, email address and photo. It does not expose job title, phone numbers, group memberships, sign-in data or any other attribute.
  • DataCentral only reads users who are members of a linked group. It does not search or list your directory.

Grant the permission​

  1. Open the Microsoft Entra admin center > App registrations > your app > API permissions.
  2. Select Add a permission > Microsoft Graph > Application permissions.
  3. Search for User.ReadBasic.All, select it and select Add permissions.
  4. Select Grant admin consent for your tenant. The permission is inactive until consent is granted.
Keep the API permissions list short

Do not grant GroupMember.ReadWrite.All, Group.ReadWrite.All or Directory.Read.All to the app. They are tenant-wide, override the AU boundary and make the custom role pointless.

Alternative

If you need more user properties, such as userPrincipalName, use a second custom role that holds only microsoft.directory/users/standard/read, assigned at Directory scope. Do not add it to the AU-scoped role, because users are not in the AU.

Step 6: Verify the configuration​

Check four places in the Microsoft Entra admin center.

CheckPathWhat you should see
Role permissionsRoles & admins > Roles & admins > your custom role > DescriptionOnly the three actions: groups/members/update, groups/members/read, groups/standard/read.
AU contentsRoles & admins > Admin units > your AU > GroupsExactly the groups you named.
AssignmentAdmin units > your AU > Roles and administrators > your custom roleThe service principal, listed as an Active assignment at AU scope.
API permissionsApp registrations > your app > API permissionsUser.ReadBasic.All with admin consent granted, and no broader group or directory permissions.

Or verify from PowerShell. Replace the placeholders with your IDs:

Get-MgDirectoryAdministrativeUnitMember -AdministrativeUnitId <au-id> -All

Get-MgRoleManagementDirectoryRoleAssignment `
-Filter "principalId eq '<service-principal-object-id>'" -All |
Format-List PrincipalId, RoleDefinitionId, DirectoryScopeId

DirectoryScopeId must read /administrativeUnits/<au-id>. A value of / means tenant-wide scope, which you do not want.

Step 7: Connect DataCentral​

  1. Enter the tenant ID, client ID and client secret in DataCentral as described in Configure DataCentral.
  2. In the Entra admin center, go to Groups > your group > Overview and copy the Object ID.
  3. In DataCentral, go to Administration > Organizational Units and select Add root unit.
  4. Turn on Entra ID group, paste the Object ID in Name or object ID of group, then select Save. DataCentral reads the group's name and creates the OU under that name, marked with an icon.
  5. Select the OU, then select Preview comparison. DataCentral reads the group's members from Entra ID and lists the differences with the OU. Select Confirm to apply them in DataCentral.
Use the Object ID

Use the Object ID, not the group name. Looking up a group by name requires tenant-wide group read access, which this setup deliberately does not grant. The group must also be in the administrative unit. To link more groups later, add them to the AU first. See Add more groups later.

The comparison and the sync only read from Entra ID. They change the OU in DataCentral, not the security group.

Troubleshooting​

SymptomCause and fix
Authorization_RequestDenied or insufficient privilegesThe signed-in account lacks Privileged Role Administrator or Global Administrator, or consent for the four permissions is missing.
Licence error when creating the roleThe tenant needs Entra ID P1 or higher for custom roles.
A positional parameter cannot be foundGroup names are separated by a space. Separate them with commas: "Group-A","Group-B".
Cannot convert value to type System.Guid-ServicePrincipalClientId received a name or malformed value. Pass the Application (client) ID.
No service principal with client ID was foundThe client ID is wrong, or the app has no service principal in this tenant. Copy the Application (client) ID from App registrations or Enterprise applications.
Group is role-assignableNot supported with AU-scoped custom roles. Choose a different group or manage membership with a Privileged Role Administrator.
Group is dynamic or synced from ADMembers cannot be edited manually in Entra ID. Change the rule or manage members on-premises.
Multiple groups are named ...Display names are not unique. Rename one group, or adapt the script to use object IDs.
Group displayName is empty for a group in the AUThe custom role lacks groups/standard/read. Add it under Description > Edit, wait a few minutes, then try again in DataCentral.
Member displayName and mail are emptyUser.ReadBasic.All is missing or admin consent was not granted. Repeat Step 5, wait a few minutes, then try again in DataCentral.
Extra permissions warning on an existing roleA role with the same name holds more than the three expected actions. Review it, or pass a different -CustomRoleName.
Cmdlet not recognizedA Graph module is missing. Repeat Step 1.
Changes not effective yetRole assignments and permission changes can take several minutes to propagate. Wait, then try again in DataCentral.

Add more groups later​

The role assignment is on the AU, so any group you add to the AU is covered straight away. The role and the service principal need no changes.

.\Add-GroupToAdministrativeUnit.ps1 -GroupNames "SG-New-Group","SG-Another" -WhatIf
.\Add-GroupToAdministrativeUnit.ps1 -GroupNames "SG-New-Group","SG-Another"

# If your AU does not use the default name
.\Add-GroupToAdministrativeUnit.ps1 -GroupNames "SG-New-Group" -AdminUnitName "My AU"

The script applies the same group checks as the main script, skips groups that are already in the AU, and stops if the AU does not exist. It signs in with AdministrativeUnit.ReadWrite.All and Group.Read.All only.

Remove the access​

Work from the narrowest change to the widest. Removing a group from the AU does not delete the group. It only ends the service principal's access to it.

# 1. Stop managing one group
Remove-MgDirectoryAdministrativeUnitMemberByRef `
-AdministrativeUnitId $auId -DirectoryObjectId $groupId

# 2. Revoke the service principal's role assignment
$assign = Get-MgRoleManagementDirectoryRoleAssignment `
-Filter "principalId eq '$spId'" -All |
Where-Object DirectoryScopeId -eq "/administrativeUnits/$auId"
Remove-MgRoleManagementDirectoryRoleAssignment -UnifiedRoleAssignmentId $assign.Id

# 3. Delete the AU and the role, only if nothing else uses them
Remove-MgDirectoryAdministrativeUnit -AdministrativeUnitId $auId
Remove-MgRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $roleId

# 4. End the session
Disconnect-MgGraph

To remove the user-read permission, open App registrations > your app > API permissions, select User.ReadBasic.All and select Remove permission. Removing the permission also removes its admin consent.

Cmdlet names follow the current Microsoft Graph PowerShell SDK. If your version differs, find the match with Get-Command *MgDirectoryAdministrativeUnit*.