Private/New-AzureUtilsPolicyNonCompliantQuery.ps1

function New-AzureUtilsPolicyNonCompliantQuery {
    <#
        .SYNOPSIS
            Builds the Resource Graph (KQL) query for policy-non-compliant resources.
        .DESCRIPTION
            Pure, side-effect-free. Reads the 'policyresources' table (policy state
            records) and keeps the resources whose latest compliance state is
            'NonCompliant', projecting the offending assignment/definition and a
            human-readable reason. The resource short name is derived from the last
            segment of the resource id.
        .OUTPUTS
            System.String (the KQL query)
    #>

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

    return @'
policyresources
| where type =~ 'microsoft.policyinsights/policystates'
| where tostring(properties.complianceState) =~ 'NonCompliant'
| extend __seg = split(tostring(properties.resourceId), '/')
| extend resName = tostring(__seg[array_length(__seg) - 1])
| extend reason = strcat('Non-compliant with policy assignment: ', tostring(properties.policyAssignmentName))
| project
    resourceId = tostring(properties.resourceId),
    resName,
    resourceType = tostring(properties.resourceType),
    resourceGroup = tostring(properties.resourceGroup),
    location = tostring(properties.resourceLocation),
    subscriptionId,
    policyAssignment = tostring(properties.policyAssignmentName),
    policyDefinition = tostring(properties.policyDefinitionName),
    reason
'@

}