Can't Add PIM Role Assignments with PowerShell? Here's Why and How to Fix It
Problem: You're trying to add a role assignment using PowerShell's Add-AzureADMSRoleAssignment cmdlet, but you're getting an error. You're certain you have the correct permissions and the target user or group exists, yet the command fails.
Simplified: You're trying to give someone permission to do something in Azure, but your PowerShell script is throwing an error, even though you think you should have access.
Scenario:
Let's say you're trying to assign the "Contributor" role to a user named "Jane Doe" in a resource group named "MyResourceGroup". Your PowerShell script looks like this:
Add-AzureADMSRoleAssignment -ObjectId "[email protected]" -RoleDefinitionId "00000000-0000-0000-0000-000000000000" -PrincipalType User -ResourceGroupName "MyResourceGroup"
The error: You might get an error message similar to this:
Add-AzureADMSRoleAssignment : The provided principal '[email protected]' is not found in the directory.
Analysis:
This error message is misleading. It's not that the user doesn't exist; it's that the cmdlet is looking in the wrong directory. The Add-AzureADMSRoleAssignment cmdlet is designed for classic Azure AD roles, not for Azure Resource Manager (ARM) roles, which is what you're likely trying to use.
Solution:
To assign roles in ARM, you need to use the New-AzureRmRoleAssignment cmdlet. Here's how to fix the script:
New-AzureRmRoleAssignment -RoleDefinitionName "Contributor" -Scope "/subscriptions/your_subscription_id/resourcegroups/MyResourceGroup" -PrincipalId (Get-AzureADUser -ObjectId "[email protected]").ObjectId
Explanation:
New-AzureRmRoleAssignment
: This cmdlet is specifically for assigning ARM roles.RoleDefinitionName
: Specify the name of the role you want to assign (e.g., "Contributor").Scope
: Provide the resource scope. In this example, it's the resource group "MyResourceGroup".PrincipalId
: Get the ObjectId of the user or group you want to assign the role to. You can use theGet-AzureADUser
cmdlet to retrieve the ObjectId based on the user's email address.
Important Notes:
- Make sure you have the necessary permissions to assign roles at the specified scope.
- Use the
Get-AzureADUser
cmdlet to retrieve the ObjectId for the user or group you want to assign the role to. - If you're working with a group, use the
Get-AzureADGroup
cmdlet instead.
Additional Tips:
- Verify role definitions: Use the
Get-AzureRmRoleDefinition
cmdlet to list available role definitions and their IDs. - Check the scope: The scope is crucial for defining the level of access. You can use the
Get-AzureRmResource
cmdlet to verify the resource scope. - Troubleshoot errors: Use
Get-AzureRmError
to get more detailed error information.
Reference:
By following these steps and using the correct cmdlet, you can successfully add PIM role assignments with PowerShell and manage your Azure access effectively.