Forum Discussion
Sagar_Lad
May 28, 2020Brass Contributor
How to add app role to using powershell to service principal
Hi All,
I would like to add app roles to my service principal in Azure AD.
1 Reply
Sort By
- Sagar_LadBrass Contributor[CmdletBinding()]Param([Parameter(Mandatory = $true)][string]$AppName,[Parameter(Mandatory = $true)][string]$token,[Parameter(Mandatory = $true)][string[]] $AllowedMemberTypes)try {#Connect-AzureADInstall-Module -Name AzureAD -Scope CurrentUser -Force$currentAzureContext = Get-AzContext$tenantId = $currentAzureContext.Tenant.Id$accountId = $currentAzureContext.Account.IdConnect-AzureAD -AadAccessToken $token -AccountId $accountId -TenantId $tenantId# Create an application role of given name and description$Id = [Guid]::NewGuid().ToString()# Create new AppRole object$newAppRole = [Microsoft.Open.AzureAD.Model.AppRole]::new()$newAppRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]$newAppRole.AllowedMemberTypes.Add("User")$newAppRole.DisplayName = "User"$newAppRole.Description = "User Role"$newAppRole.Value = "User"$newAppRole.Id = $Id$newAppRole.IsEnabled = $true# Add new AppRole and apply changes to Application object$App = Get-AzureADServicePrincipal -Filter "displayName eq '$AppName'"$appRoles = $App.AppRoles | Where-Object { $_.DisplayName -eq $RoleToAssign }echo $appRoles$SPNObjectId=(Get-AzADServicePrincipal -DisplayNameBeginsWith $AppName).Idecho $SPNObjectId$appRoles += $newAppRoleecho $appRolesSet-AzureADApplication -ObjectId $SPNObjectId -AppRoles $appRoles}catch {$message = $Error[0].Exception.MessageWrite-Host "##vso[task.logissue type=error;]$message.";Write-Error $message;}