Functions/New-IntuneRoleAssignment.ps1
function New-IntuneRoleAssignment { <# .SYNOPSIS Creates a new role assignment for a principal in Intune. .DESCRIPTION Assigns an existing admin role to a principal by creating a role assignment via the Graph API. .PARAMETER RoleDefinitionId The ID of the admin role to assign. .PARAMETER PrincipalId The object ID of the principal (user, group, etc.) receiving the role. .PARAMETER ResourceScope (Optional) The resource scope for the assignment (default: "/"). .PARAMETER Scope (Optional) The specific scope (default: "/"). .EXAMPLE New-IntuneRoleAssignment -RoleDefinitionId "role-def-id" -PrincipalId "user-object-id" #> [CmdletBinding(DefaultParameterSetName = 'ByName')] param( [Parameter(Mandatory = $true)] [string]$RoleAssignmentName, [Parameter(Mandatory = $false, ParameterSetName = 'ById')] [string]$RoleDefinitionId, [Parameter(Mandatory = $true, ParameterSetName = 'ByName')] [string]$RoleDefinitionName, [Parameter(Mandatory = $true)] [string]$Description, [Parameter(Mandatory = $true)] [string]$RoleGroupName, [Parameter(Mandatory = $true)] [string]$ScopeTagName ) # Check if connected to Microsoft Graph if (-not (Get-MgContext -ErrorAction SilentlyContinue)) { Write-Error "You must run Connect-IntuneGraph before calling this function." return } # Create Role Assignments If ($ExistingAssignment = Get-MgBetaDeviceManagementRoleAssignment -Filter "displayName eq '$RoleAssignmentName'") { Remove-MgBetaDeviceManagementRoleAssignment -DeviceAndAppManagementRoleAssignmentId $($ExistingAssignment.Id) Write-Host "Removing existing role assignment $RoleAssignmentName." -ForegroundColor Yellow } # Single Scope Tag for the Organization $ScopeTags = @( "https://graph.microsoft.com/beta/deviceManagement/roleScopeTags('$((Get-MgBetaDeviceManagementRoleScopeTag ` -Filter "DisplayName eq '$ScopeTagName'").Id)')" ) If (!($RoleDefinitionId)) { $RoleDefinitionId = $((Get-MgBetaDeviceManagementRoleDefinition -Filter "DisplayName eq '$RoleDefinitionName'").Id) } $RoleAssignmentParams = @{ id = "" description = $Description displayName = $RoleAssignmentName members = @( $((Get-MgBetaGroup -Filter "DisplayName eq '$RoleGroupName'").Id) ) resourceScopes = @( ) "roleDefinition@odata.bind" = "https://graph.microsoft.com/beta/deviceManagement/roleDefinitions('$RoleDefinitionId')" scopeType = "allDevices" "roleScopeTags@odata.bind" = $ScopeTags } New-MgBetaDeviceManagementRoleAssignment -BodyParameter $RoleAssignmentParams } |