How to Assign an App-Scoped Role to a User Using PowerShell?

0
5
Asked By TechieTurtle42 On

I'm trying to assign the "Application Administrator" role to a specific user and scope it to a designated application via PowerShell. In the graphical interface, this is done by navigating to Users, selecting the user, and adding the role assignment there. However, I'm having trouble translating that to PowerShell. Here's the code I'm currently using:

```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, when I run this code, I get an error stating that the expected property 'appScopeId' is missing from the resource type 'RoleAssignment'. Any insights on what I might be doing wrong? I appreciate any help!

2 Answers

Answered By CodeWiz91 On

You might want to avoid using backticks in your PowerShell script. Here’s a cleaner way to rewrite your code:

```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'"

$RoleSplat = @{
PrincipalId = $userId.Id
RoleDefinitionId = $Role.Id
AppScopeId = $App.Id
}

New-MgRoleManagementDirectoryRoleAssignment @RoleSplat
```

This should help with readability and possibly avoid some syntax issues. Just a heads up, ensure all variables are being populated correctly!

Answered By ScriptingNinja On

Even though the command has multiple parameters, I've noticed that Microsoft's examples often use the `-BodyParameter` option. It's possible the other parameters might not function as expected right now. Try updating your script to use `-BodyParameter`:

```powershell
$params = @{
"@odata.type" = "#microsoft.graph.unifiedRoleAssignment"
principalId = $userId
roleDefinitionId = $Role.Id
appScopeId = $App.Id
}
New-MgRoleManagementDirectoryRoleAssignment -BodyParameter $params
```
You should also check the values of your variables to make sure they're correct before running this again.

OriginalQuestioner -

Thanks for the tip! I've tried that method, but I still get the same error regarding 'appScopeId'. I confirmed that all the IDs are correct too.

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.