Skip to content

Instantly share code, notes, and snippets.

@khazeamo
Last active October 21, 2024 11:38
Show Gist options
  • Save khazeamo/d89bb1a323bda9a141f43dabd132af73 to your computer and use it in GitHub Desktop.
Save khazeamo/d89bb1a323bda9a141f43dabd132af73 to your computer and use it in GitHub Desktop.
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Applications
[CmdletBinding()]
param (
# Name, application ID or object ID of the managed identity
[Parameter(Mandatory = $true)]
[string]
$ManagedIdentity,
# Name or ID of the Graph API permission (application role)
[Parameter(Mandatory = $true)]
[string[]]
$Role,
[Parameter(Mandatory = $false)]
[guid]
$TenantId
)
$ErrorActionPreference = 'Stop'
Connect-MgGraph -Tenant $TenantId -NoWelcome
$graph = Get-MgServicePrincipalByAppId -AppId '00000003-0000-0000-c000-000000000000'
$identity = [guid]::TryParse($ManagedIdentity, [ref][guid]::Empty) ?
(Get-MgServicePrincipal -Filter "Id eq '$($ManagedIdentity)' or AppId eq '$($ManagedIdentity)'") :
(Get-MgServicePrincipal -Filter "displayName eq '$($ManagedIdentity)'")
if ($null -ne $identity) {
foreach ($r in $Role) {
if ([guid]::TryParse($r, [ref][guid]::Empty)) {
$roleName = ($graph.AppRoles | Where-Object -FilterScript { $_.AllowedMemberTypes -contains 'Application' -and $_.Id -eq $r } | Select-Object -First 1).Value
$roleId = $r
}
else {
$roleName = $r
$roleId = ($graph.AppRoles | Where-Object -FilterScript { $_.AllowedMemberTypes -contains 'Application' -and $_.Value -eq $r } | Select-Object -First 1).Id
}
try {
New-MgServicePrincipalAppRoleAssignment -PrincipalId $identity.Id -AppRoleId $roleId -ResourceId $graph.Id -ServicePrincipalId $identity.Id
}
catch [System.Exception] {
if ($_.Exception.Message -eq '[Request_BadRequest] : Permission being assigned already exists on the object') {
Write-Warning "AppRole assignment '$($roleName) ($($roleId))' already exists for $($identity.DisplayName) and will not be added"
}
else {
$_
}
}
}
}
else {
Write-Error -Exception "Could not find identity '$($ManagedIdentity)'"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment