Goal
You have hundreds of subscriptions and the Defender for Cloud portal shows thousands of recommendations. You need answers you can script: which resources are unhealthy, who owns them, how the secure score is moving, which alerts are still active, which plans are off, and how to exempt a finding without hiding it permanently.
Defender for Cloud writes its data to the securityresources table in Azure Resource Graph. The queries below run in Resource Graph Explorer or from the CLI:
az extension add --name resource-graph --upgrade
az graph query -q "<query>" --management-groups <mg-id> --first 1000 -o table
Use --management-groups (or --subscriptions) to set the scope. Without it, the query covers only the subscriptions your current context can see.
Tip
Resource Graph returns at most 1,000 rows per page. For bigger result sets, page with
--skip-token, orsummarizefirst and drill down afterwards.
Recommendations (assessments)
Unhealthy resources by recommendation and severity
securityresources
| where type == "microsoft.security/assessments"
| extend status = tostring(properties.status.code),
severity = tostring(properties.metadata.severity),
recommendation = tostring(properties.displayName)
| where status == "Unhealthy"
| summarize unhealthy = count() by recommendation, severity
| extend sevRank = case(severity == "High", 1, severity == "Medium", 2, 3)
| order by sevRank asc, unhealthy desc
Status codes are Healthy, Unhealthy and NotApplicable. For NotApplicable, properties.status.cause says why. An exempted resource also shows up as not applicable, with an exemption cause.
One row per unhealthy resource, with owner tags
securityresources
| where type == "microsoft.security/assessments"
| where tostring(properties.status.code) == "Unhealthy"
| extend resourceId = tolower(tostring(properties.resourceDetails.Id)),
recommendation = tostring(properties.displayName),
severity = tostring(properties.metadata.severity)
| where severity == "High"
| join kind=leftouter (
resources
| project resourceId = tolower(id), owner = tostring(tags["owner"]), env = tostring(tags["env"])
) on resourceId
| project subscriptionId, resourceId, recommendation, severity, owner, env
| order by owner asc
Swap owner and env for your own tag names. For non-Azure resources (AWS or GCP connectors), properties.resourceDetails.Source is not Azure, and the ID is in a different field. Filter on Source before you join.
Unhealthy count per subscription, for team dashboards
securityresources
| where type == "microsoft.security/assessments"
| where tostring(properties.status.code) == "Unhealthy"
| extend severity = tostring(properties.metadata.severity)
| summarize high = countif(severity == "High"),
medium = countif(severity == "Medium"),
low = countif(severity == "Low") by subscriptionId
| join kind=leftouter (
resourcecontainers
| where type == "microsoft.resources/subscriptions"
| project subscriptionId, subscriptionName = name
) on subscriptionId
| project subscriptionName, subscriptionId, high, medium, low
| order by high desc
Findings inside a recommendation (sub-assessments)
Vulnerability findings, such as container image CVEs or missing VM updates, are stored as sub-assessments under the parent recommendation:
securityresources
| where type == "microsoft.security/assessments/subassessments"
| extend parentAssessment = tostring(split(id, "/subAssessments/")[0]),
finding = tostring(properties.displayName),
severity = tostring(properties.status.severity),
resourceId = tostring(properties.resourceDetails.id)
| where tostring(properties.status.code) == "Unhealthy"
| summarize resources = dcount(resourceId) by finding, severity
| order by resources desc
Sub-assessment property names vary by assessment type, and some scanners use newer data paths, so check one raw row (| take 1) before you build on it.
Secure score
securityresources
| where type == "microsoft.security/securescores"
| extend percentage = todouble(properties.score.percentage),
current = todouble(properties.score.current),
maximum = todouble(properties.score.max)
| project subscriptionId, current, maximum, percentage = round(percentage * 100, 1)
| order by percentage asc
Score per security control, to see which control gives the biggest gain:
securityresources
| where type == "microsoft.security/securescores/securescorecontrols"
| extend control = tostring(properties.displayName),
current = todouble(properties.score.current),
maximum = todouble(properties.score.max),
unhealthy = toint(properties.unhealthyResourceCount)
| summarize potentialGain = sum(maximum - current), unhealthy = sum(unhealthy) by control
| order by potentialGain desc
Resource Graph shows only the current state. For a score trend, export the data on a schedule (see "Prevent it next time").
Security alerts
securityresources
| where type == "microsoft.security/locations/alerts"
| where tostring(properties.Status) == "Active"
| extend severity = tostring(properties.Severity),
alert = tostring(properties.AlertDisplayName),
started = todatetime(properties.StartTimeUtc)
| where severity in ("High", "Medium")
| project started, severity, alert, subscriptionId,
resource = tostring(properties.CompromisedEntity)
| order by started desc
Alert property names start with capital letters (Status, Severity), unlike assessments. Triage them in the portal or your SIEM. This query is for finding what is still open across the fleet.
Defender plan coverage
Resource Graph doesn't hold pricing tiers. Use the CLI for each subscription:
for SUB in $(az account list --query "[?state=='Enabled'].id" -o tsv); do
az security pricing list --subscription "$SUB" \
--query "value[].{sub:'$SUB', plan:name, tier:pricingTier, subPlan:subPlan}" -o tsv
done
The output shape varies between CLI versions. If value[] returns nothing, run the command once with -o json and adjust the query. Look for Free on plans you expect to be Standard, such as VirtualMachines, StorageAccounts, SqlServers, Containers and KeyVaults.
Caution
Enabling a plan with
az security pricing create -n <plan> --tier standardstarts billing straight away for every eligible resource in the subscription. Check current pricing and get the cost approved before running it in a loop.
Exemptions that expire
Most Defender recommendations come from the Microsoft cloud security benchmark initiative. It is assigned to each subscription as SecurityCenterBuiltIn. To exempt a single resource, create a policy exemption against that assignment.
1. Find the policy definition reference ID
SUB="<sub-id>"
SET_ID=$(az policy assignment show --name SecurityCenterBuiltIn \
--scope "/subscriptions/$SUB" --query policyDefinitionId -o tsv)
az policy set-definition show --name "${SET_ID##*/}" \
--query "policyDefinitions[].{ref:policyDefinitionReferenceId, def:policyDefinitionId}" -o table
Match it to the recommendation with properties.metadata.policyDefinitionId from the assessment, where that field is populated.
2. Create a scoped exemption with an expiry date
az policy exemption create \
--name exempt-vm-legacy01-endpoint \
--scope "/subscriptions/$SUB/resourceGroups/rg-legacy/providers/Microsoft.Compute/virtualMachines/vm-legacy01" \
--policy-assignment "/subscriptions/$SUB/providers/Microsoft.Authorization/policyAssignments/SecurityCenterBuiltIn" \
--policy-definition-reference-ids "<reference-id>" \
--exemption-category Mitigated \
--expires-on "2027-03-31T00:00:00Z" \
--description "Compensating control: isolated VLAN, ticket CHG-12345"
Use Mitigated when a compensating control is in place, and Waiver when you accept the risk. The exempted resource can take some time to move out of the unhealthy list.
3. Review exemptions that are expiring or have no expiry
policyresources
| where type == "microsoft.authorization/policyexemptions"
| extend expiresOn = todatetime(properties.expiresOn),
category = tostring(properties.exemptionCategory),
assignment = tostring(properties.policyAssignmentId)
| where assignment endswith "/securitycenterbuiltin"
| where isnull(expiresOn) or expiresOn < now() + 30d
| project name, category, expiresOn, scope = tostring(split(id, "/providers/Microsoft.Authorization/policyExemptions/")[0])
Quick reference
| Question | Table and type |
|---|---|
| Unhealthy resources | securityresources, microsoft.security/assessments |
| CVEs and findings | securityresources, microsoft.security/assessments/subassessments |
| Secure score | securityresources, microsoft.security/securescores |
| Score per control | securityresources, microsoft.security/securescores/securescorecontrols |
| Active alerts | securityresources, microsoft.security/locations/alerts |
| Exemptions | policyresources, microsoft.authorization/policyexemptions |
| Plan tiers | az security pricing list (not in Resource Graph) |
Prevent it next time
- Set up continuous export of recommendations, secure score and alerts to a Log Analytics workspace, so you have history for trends and alerting. Resource Graph shows only the current state.
- Route each team's unhealthy High findings to that team, using the owner-tag query on a weekly schedule.
- Require an
--expires-ondate and a ticket reference on every exemption, and review the expiring-exemptions query monthly. - Check plan coverage when you create a subscription. Assigning the built-in policies that enable Defender plans keeps new subscriptions from starting on
Free.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get