Created
December 16, 2024 12:43
-
-
Save AlexanderHolmeset/d990f4c3ada28120df1da016ce6cdee1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Requires -Modules Microsoft.Graph | |
# Install the module. (You need admin on the machine.) | |
# Install-Module Microsoft.Graph | |
# Set Static Variables | |
$TenantID="Enter your Tenant ID" | |
$LogicAppDisplayname = "NewCopilotUserEmail" | |
# Define dynamic variables | |
$ServicePrincipalFilter = "displayName eq '$($LogicAppDisplayname)'" | |
$GraphAPIAppName = "Microsoft Graph" | |
$ApiServicePrincipalFilter = "displayName eq '$($GraphAPIAppName)'" | |
# Scopes needed for the managed identity (Add other scopes if needed) | |
$Scopes = @( | |
"GroupMember.Read.All","User.Read.All","Mail.Send" | |
) | |
# Connect to MG Graph - scopes must be consented the first time you run this. | |
# Connect with Global Administrator | |
Connect-MgGraph -Scopes "Application.Read.All","AppRoleAssignment.ReadWrite.All" -TenantId $TenantID -UseDeviceAuthentication | |
# Get the service principal for your managed identity. | |
$ServicePrincipal = Get-MgServicePrincipal -Filter $ServicePrincipalFilter | |
# Get the service principal for Microsoft Graph. | |
# Result should be AppId 00000003-0000-0000-c000-000000000000 | |
$ApiServicePrincipal = Get-MgServicePrincipal -Filter "$ApiServicePrincipalFilter" | |
# Apply permissions | |
Foreach ($Scope in $Scopes) { | |
Write-Host "`nGetting App Role '$Scope'" | |
$AppRole = $ApiServicePrincipal.AppRoles | Where-Object {$_.Value -eq $Scope -and $_.AllowedMemberTypes -contains "Application"} | |
if ($null -eq $AppRole) { Write-Error "Could not find the specified App Role on the Api Service Principal"; continue; } | |
if ($AppRole -is [array]) { Write-Error "Multiple App Roles found that match the request"; continue; } | |
Write-Host "Found App Role, Id '$($AppRole.Id)'" | |
$ExistingRoleAssignment = Get-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $ServicePrincipal.Id | Where-Object { $_.AppRoleId -eq $AppRole.Id } | |
if ($null -eq $existingRoleAssignment) { | |
New-MgServicePrincipalAppRoleAssignment -ServicePrincipalId $ServicePrincipal.Id -PrincipalId $ServicePrincipal.Id -ResourceId $ApiServicePrincipal.Id -AppRoleId $AppRole.Id | |
} else { | |
Write-Host "App Role has already been assigned, skipping" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment