Private/New-AzureUtilsRoleAssignmentQuery.ps1

function New-AzureUtilsRoleAssignmentQuery {
    <#
        .SYNOPSIS
            Builds the Resource Graph (KQL) query that lists all role assignments.
        .DESCRIPTION
            Pure, side-effect-free. Reads the 'authorizationresources' table and
            projects every role assignment's principal, role and scope. It does NOT
            decide which are stale - the ARG 'principalType' is frozen at creation
            time and does not change when the principal is deleted, so orphaned
            assignments are detected by resolving each principalId against Entra ID
            (see Get-AzureUtilsExistingPrincipal), not from the query.
        .OUTPUTS
            System.String (the KQL query)
    #>

    [CmdletBinding()]
    [OutputType([string])]
    param()

    return @'
authorizationresources
| where type =~ 'microsoft.authorization/roleassignments'
| extend __rd = split(tostring(properties.roleDefinitionId), '/')
| project
    id = id,
    principalId = tostring(properties.principalId),
    principalType = tostring(properties.principalType),
    scope = tostring(properties.scope),
    roleDefinitionId = tostring(__rd[array_length(__rd) - 1]),
    subscriptionId
'@

}