AzureAD PowerShell New-AzureRmRoleAssignment keeps failing

EDIT:

Ok, the previous "solution" was pure luck... Apparently, the New-AzureRmADServicePrincipal is created asynchronously. That method does immediately return an object, but the actual principal isn't created immediately...

I worked around this by adding a Start-Sleep -s 15 command.

If this isn't enough, either increase it, or catch the error and wait another few seconds before trying again.


I had the same error but the route cause and solution was different. This was my code:

New-AzureRmRoleAssignment -ObjectId $ServicePrincipal.ApplicationId -RoleDefinitionName $Role -Scope "/subscriptions/$($Subscription.Context.Subscription.Id)"

and it always failed with the same error:

New-AzureRmRoleAssignment : Principal 7dfxxxxxxxxxxxxx1b1 does not exist in the directory 3141xxxxxxxxxxxxxx736.

Waiting did not help.

The issue was resolved by using $ServicePrincipal.Id instead of $ServicePrincipal.ApplicationId for the -ObjectId parameter

Using $ServicePrincipal.ApplicationId is suggested by Example 5 at https://docs.microsoft.com/en-us/powershell/module/azurerm.resources/new-azurermroleassignment?view=azurermps-5.5.0 which is not correct..