I'm trying to execute this in an Azure Automation runbook
$app = Get-AzureADApplication -ObjectId $ApplicationId
$appRole = New-Object Microsoft.Open.AzureAD.Model.AppRole
$appRole.AllowedMemberTypes = New-Object System.Collections.Generic.List[string]
$appRole.AllowedMemberTypes.Add("User");
$appRole.DisplayName = $TenantName + " Users"
$appRole.Id = New-Guid
$appRole.IsEnabled = $true
$appRole.Description = "Users of the tenant"
$appRole.Value = $TenantName
$app.AppRoles.Add($appRole)
Set-AzureADApplication -ObjectId $ApplicationId -AppRoles $app.AppRoles
Reading the application works fine, when I print the app variable I can see it's the correct application. Executing the script from my own machine also gives no errors. Yet executing it via the runbook gives me:
Set-AzureADApplication : Error occurred while executing SetApplication
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.
HttpStatusCode: Forbidden
HttpStatusDescription: Forbidden
HttpResponseStatus: Completed
By now I have given the automation application registration in Azure AD all rights of the Active Directory API. I have also clicked "Grant Permissions". I know it's the correct app registration because the script also invites an external user, when I gave the correct rights on the "Graph Api" that started to work.
I tried out your exact script in a run book and to make it work, I had to add code to "Login as the service principal" just before your PowerShell script. You can see more details here: Using Azure Run As Account in Azure Automation
On the permissions front, I only gave 1 application permission (i.e. "Read and write all applications") and then clicked "Grant Permissions" as it did need Admin consent. Steps were done by a user with "Global administrator" directory role in my Azure AD.
Here is my final working PowerShell script (copied from edit runbook):
Here are screenshots from some other important steps that I followed, which you may or may not have done already.
Create Azure Run As account while creating automation account
Make sure account settings for your automation account has the run as accounts now.
Find the App Registration created for Run as Account and give it permission to read and write all Azure AD applications.