How to Assign a Scoped Role to a User in PowerShell?

0
4
Asked By TechieNinja84 On

I'm trying to assign the "Application Administrator" role to a specific user and scope it to a particular application using PowerShell. In the GUI, this is done through Users > RandomUser > Assigned Roles > Add Assignment. Here's the code I have so far:

```powershell
$userUPN = '[email protected]'
$roleName = 'Application Administrator'
$appName = 'App1'
$App = Get-MgServicePrincipal -Filter "displayName eq '$appName'"
$Role = Get-MgDirectoryRole | Where-Object {$_.displayName -eq $roleName}
$userId = (Get-MgUser -Filter "userPrincipalName eq '$userUPN'").Id

New-MgRoleManagementDirectoryRoleAssignment -PrincipalId $userId -RoleDefinitionId $Role.Id -AppScopeId $App.Id
```

However, upon executing this code, I receive the following error:

`New-MgRoleManagementDirectoryRoleAssignment_CreateExpanded: Expected property 'appScopeId' is not present on resource of type 'RoleAssignment'`

I've tried searching online for solutions but haven't found much. Any insights on what's going wrong here?

2 Answers

Answered By AdminGuru111 On

From my experience, it seems like Microsoft's examples typically utilize `-BodyParameter` instead of individual parameters. Try changing your command to use `-BodyParameter` like this:

```powershell
$params = @{
"@odata.type" = "#microsoft.graph.unifiedRoleAssignment"
principalId = (Get-MgUser -Filter "userPrincipalName eq '$userUPN' ").Id
roleDefinitionId = (Get-MgDirectoryRole | Where-Object {$_.displayName -eq $roleName}).Id
directoryScopeId = (Get-MgServicePrincipal -Filter "displayName eq '$appName' ").Id
}
New-MgRoleManagementDirectoryRoleAssignment -BodyParameter $params
```
Be sure to also check that your variable values are all correct before running this. Sometimes the cmdlet parameters differ in functionality!

UserHelper320 -

I tried your suggestion, but it still throws the same error about `appScopeID`. My variables are all populated correctly as well. What should I do next?

Answered By CodeWhiz92 On

One thing to note is that using backticks for line continuation can be a bit confusing in PowerShell. You might want to rewrite your script without them. Here’s an example of how to simplify your code:

```powershell
$RoleSplat = @{
PrincipalId = (Get-MgUser -Filter "userPrincipalName eq '$userUPN' ").Id
RoleDefinitionId = (Get-MgDirectoryRole | Where-Object {$_.displayName -eq $roleName}).Id
AppScopeId = (Get-MgServicePrincipal -Filter "displayName eq '$appName' ").Id
}
New-MgRoleManagementDirectoryRoleAssignment @RoleSplat
```
This way, you can avoid potential syntax issues with backticks and clean up the command a bit. Good luck!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.