Created
June 26, 2025 07:51
-
-
Save AlexanderHolmeset/2f7e2266608d8d266ebd70c4850a49c1 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 here" | |
$AutomationAccountDisplayname ="Enter your Automation Account Display Name here" | |
# Define dynamic variables | |
$ServicePrincipalFilter = "displayName eq '$($AutomationAccountDisplayname)'" | |
$GraphAPIAppName = "Microsoft Graph" | |
$ApiServicePrincipalFilter = "displayName eq '$($GraphAPIAppName)'" | |
# Scopes needed for the managed identity (Add other scopes if needed) | |
$Scopes = @( | |
"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 -UseDeviceCode | |
# 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