Query di esempio di Azure Resource Graph per categoria

Questa pagina è una raccolta di query di esempio di Azure Resource Graph raggruppate per categorie di servizi e generali. Per passare a una categoria specifica, usare i collegamenti nella parte superiore della pagina. Altrimenti, premere CTRL-F per usare la funzionalità di ricerca del browser.

Azure Advisor

Ottenere un riepilogo dei risparmi sui costi da Azure Advisor

Questa query riepiloga i risparmi sui costi di ogni raccomandazione di Azure Advisor.

AdvisorResources
| where type == 'microsoft.advisor/recommendations'
| where properties.category == 'Cost'
| extend
	resources = tostring(properties.resourceMetadata.resourceId),
	savings = todouble(properties.extendedProperties.savingsAmount),
	solution = tostring(properties.shortDescription.solution),
	currency = tostring(properties.extendedProperties.savingsCurrency)
| summarize
	dcount(resources),
	bin(sum(savings), 0.01)
	by solution, currency
| project solution, dcount_resources, sum_savings, currency
| order by sum_savings desc
az graph query -q "AdvisorResources | where type == 'microsoft.advisor/recommendations' | where properties.category == 'Cost' | extend resources = tostring(properties.resourceMetadata.resourceId), savings = todouble(properties.extendedProperties.savingsAmount), solution = tostring(properties.shortDescription.solution), currency = tostring(properties.extendedProperties.savingsCurrency) | summarize dcount(resources), bin(sum(savings), 0.01) by solution, currency | project solution, dcount_resources, sum_savings, currency | order by sum_savings desc"

Servizio app di Azure

Elencare la versione TLS del servizio app Azure

Elencare la versione minima di Transport Layer Security (TLS) del servizio app Azure per le richieste in ingresso a un'app Web.

AppServiceResources
| where type =~ 'microsoft.web/sites/config'
| project id, name, properties.MinTlsVersion
az graph query -q "AppServiceResources | where type =~ 'microsoft.web/sites/config' | project id, name, properties.MinTlsVersion"

Azure Arc

Ottenere i tipi di risorse abilitati per Azure Arc per i percorsi personalizzati abilitati per Azure Arc

Fornisce un elenco dei tipi di risorse abilitati per i percorsi personalizzati abilitati per Azure Arc.

ExtendedLocationResources
| where type == 'microsoft.extendedlocation/customlocations/enabledresourcetypes'
az graph query -q "ExtendedLocationResources | where type == 'microsoft.extendedlocation/customlocations/enabledresourcetypes'"

Elencare le posizioni personalizzate abilitate per Azure Arc con VMware o SCVMM abilitato

Fornisce un elenco di tutte le posizioni personalizzate abilitate per Azure Arc con tipi di risorse VMware o SCVMM abilitati.

Resources
| where type =~ 'microsoft.extendedlocation/customlocations' and properties.provisioningState =~ 'succeeded'
| extend clusterExtensionIds=properties.clusterExtensionIds
| mvexpand clusterExtensionIds
| extend clusterExtensionId = tolower(clusterExtensionIds)
| join kind=leftouter(
	ExtendedLocationResources
	| where type =~ 'microsoft.extendedlocation/customLocations/enabledResourcetypes'
	| project clusterExtensionId = tolower(properties.clusterExtensionId), extensionType = tolower(properties.extensionType)
	| where extensionType in~ ('microsoft.scvmm','microsoft.vmware')
) on clusterExtensionId
| where extensionType in~ ('microsoft.scvmm','microsoft.vmware')
| summarize virtualMachineKindsEnabled=make_set(extensionType) by id,name,location
| sort by name asc
az graph query -q "Resources | where type =~ 'microsoft.extendedlocation/customlocations' and properties.provisioningState =~ 'succeeded' | extend clusterExtensionIds=properties.clusterExtensionIds | mvexpand clusterExtensionIds | extend clusterExtensionId = tolower(clusterExtensionIds) | join kind=leftouter( ExtendedLocationResources | where type =~ 'microsoft.extendedlocation/customLocations/enabledResourcetypes' | project clusterExtensionId = tolower(properties.clusterExtensionId), extensionType = tolower(properties.extensionType) | where extensionType in~ ('microsoft.scvmm','microsoft.vmware') ) on clusterExtensionId | where extensionType in~ ('microsoft.scvmm','microsoft.vmware') | summarize virtualMachineKindsEnabled=make_set(extensionType) by id,name,location | sort by name asc"

Kubernetes con abilitazione di Azure Arc

Elencare tutti i cluster Kubernetes abilitati per Azure Arc con l'estensione Monitoraggio di Azure

Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc in cui è installata l'estensione Monitoraggio di Azure.

KubernetesConfigurationResources
| where type == 'microsoft.kubernetesconfiguration/extensions'
| where properties.ExtensionType  == 'microsoft.azuremonitor.containers'
| parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' *
| project connectedClusterId
az graph query -q "KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' * | project connectedClusterId"

Elencare tutti i cluster Kubernetes abilitati per Azure Arc senza l'estensione Monitoraggio di Azure

Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc che manca l'estensione Monitoraggio di Azure.

Resources
| where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId
| join kind = leftouter
	(KubernetesConfigurationResources
	| where type == 'microsoft.kubernetesconfiguration/extensions'
	| where properties.ExtensionType  == 'microsoft.azuremonitor.containers'
	| parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' *
	| project connectedClusterId
)  on connectedClusterId
| where connectedClusterId1 == ''
| project connectedClusterId
az graph query -q "Resources | where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId | join kind = leftouter (KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' * | project connectedClusterId ) on connectedClusterId | where connectedClusterId1 == '' | project connectedClusterId"

Elencare tutte le risorse Kubernetes abilitate per Azure Arc

Restituisce un elenco di ogni cluster Kubernetes abilitato per Azure Arc e dei metadati pertinenti per ogni cluster.

Resources
| project id, subscriptionId, location, type, properties.agentVersion, properties.kubernetesVersion, properties.distribution, properties.infrastructure, properties.totalNodeCount, properties.totalCoreCount
| where type =~ 'Microsoft.Kubernetes/connectedClusters'
az graph query -q "Resources | project id, subscriptionId, location, type, properties.agentVersion, properties.kubernetesVersion, properties.distribution, properties.infrastructure, properties.totalNodeCount, properties.totalCoreCount | where type =~ 'Microsoft.Kubernetes/connectedClusters'"

Elencare tutti i Connessione edClusters e ManagedClusters che contengono una configurazione Flux

Restituisce gli ID connectedCluster e managedCluster per i cluster che contengono almeno un fluxConfiguration.

resources
| where type =~ 'Microsoft.Kubernetes/connectedClusters' or type =~ 'Microsoft.ContainerService/managedClusters' | extend clusterId = tolower(id) | project clusterId
| join
( kubernetesconfigurationresources
| where type == 'microsoft.kubernetesconfiguration/fluxconfigurations'
| parse tolower(id) with clusterId '/providers/microsoft.kubernetesconfiguration/fluxconfigurations' *
| project clusterId
) on clusterId
| project clusterId
az graph query -q "resources | where type =~ 'Microsoft.Kubernetes/connectedClusters' or type =~ 'Microsoft.ContainerService/managedClusters' | extend clusterId = tolower(id) | project clusterId | join ( kubernetesconfigurationresources | where type == 'microsoft.kubernetesconfiguration/fluxconfigurations' | parse tolower(id) with clusterId '/providers/microsoft.kubernetesconfiguration/fluxconfigurations' * | project clusterId ) on clusterId | project clusterId"

Elencare tutte le configurazioni Flux in uno stato non conforme

Restituisce gli ID fluxConfiguration delle configurazioni che non riescono a sincronizzare le risorse nel cluster.

kubernetesconfigurationresources
| where type == 'microsoft.kubernetesconfiguration/fluxconfigurations'
| where properties.complianceState == 'Non-Compliant'
| project id
az graph query -q "kubernetesconfigurationresources | where type == 'microsoft.kubernetesconfiguration/fluxconfigurations' | where properties.complianceState == 'Non-Compliant' | project id"

Server con abilitazione di Azure Arc

Ottenere il conteggio e la percentuale di server abilitati per Arc per dominio

Questa query riepiloga la proprietà domainName nei server abilitati per Azure Arc e usa un calcolo con bin per creare una colonna Pct per la percentuale di server abilitati per Arc per ogni dominio.

Resources
| where type == 'microsoft.hybridcompute/machines'
| project domain=tostring(properties.domainName)
| summarize Domains=make_list(domain), TotalMachineCount=sum(1)
| mvexpand EachDomain = Domains
| summarize PerDomainMachineCount = count() by tostring(EachDomain), TotalMachineCount
| extend Pct = 100 * bin(todouble(PerDomainMachineCount) / todouble(TotalMachineCount), 0.001)
az graph query -q "Resources | where type == 'microsoft.hybridcompute/machines' | project domain=tostring(properties.domainName) | summarize Domains=make_list(domain), TotalMachineCount=sum(1) | mvexpand EachDomain = Domains | summarize PerDomainMachineCount = count() by tostring(EachDomain), TotalMachineCount | extend Pct = 100 * bin(todouble(PerDomainMachineCount) / todouble(TotalMachineCount), 0.001)"

Elencare tutte le estensioni installate in un server abilitato per Azure Arc

Prima di tutto, questa query usa project nel tipo di risorsa del computer ibrido per ottenere l'ID in maiuscolo (toupper()), ottenere il nome del computer e il sistema operativo in esecuzione nel computer. Ottenere l'ID risorsa in lettere maiuscole è un buon modo per prepararsi a join un'altra proprietà. Quindi, la query usa join con il tipo leftouter per ottenere le estensioni associando un carattere maiuscolo substring dell'ID di estensione. La parte dell'ID prima /extensions/<ExtensionName> è lo stesso formato dell'ID computer ibrido, quindi viene usata questa proprietà per .join summarize viene quindi usato con sul make_list nome dell'estensione macchina virtuale per combinare il nome di ogni estensione in cui ID, OSName e ComputerName sono uguali in una singola proprietà di matrice. Infine, si ordina in base a OSName minuscolo con asc. Per impostazione predefinita, order by è decrescente.

Resources
| where type == 'microsoft.hybridcompute/machines'
| project
	id,
	JoinID = toupper(id),
	ComputerName = tostring(properties.osProfile.computerName),
	OSName = tostring(properties.osName)
| join kind=leftouter(
	Resources
	| where type == 'microsoft.hybridcompute/machines/extensions'
	| project
		MachineId = toupper(substring(id, 0, indexof(id, '/extensions'))),
		ExtensionName = name
) on $left.JoinID == $right.MachineId
| summarize Extensions = make_list(ExtensionName) by id, ComputerName, OSName
| order by tolower(OSName) asc
az graph query -q "Resources | where type == 'microsoft.hybridcompute/machines' | project id, JoinID = toupper(id), ComputerName = tostring(properties.osProfile.computerName), OSName = tostring(properties.osName) | join kind=leftouter( Resources | where type == 'microsoft.hybridcompute/machines/extensions' | project  MachineId = toupper(substring(id, 0, indexof(id, '/extensions'))),  ExtensionName = name ) on \$left.JoinID == \$right.MachineId | summarize Extensions = make_list(ExtensionName) by id, ComputerName, OSName | order by tolower(OSName) asc"

Elencare i server abilitati per Arc che non eseguono la versione più recente dell'agente rilasciato

Questa query restituisce tutti i server abilitati per Arc che eseguono una versione obsoleta dell'agente computer Connessione ed. Gli agenti con stato Scaduto vengono esclusi dai risultati. La query usa leftouterjoin per riunire le raccomandazioni di Advisor generate su qualsiasi agente computer Connessione identificato come non aggiornato e computer ibridi per escludere tutti gli agenti che non hanno comunicato con Azure per un periodo di tempo.

AdvisorResources
| where type == 'microsoft.advisor/recommendations'
| where properties.category == 'HighAvailability'
| where properties.shortDescription.solution == 'Upgrade to the latest version of the Azure Connected Machine agent'
| project
		id,
		JoinId = toupper(properties.resourceMetadata.resourceId),
		machineName = tostring(properties.impactedValue),
		agentVersion = tostring(properties.extendedProperties.installedVersion),
		expectedVersion = tostring(properties.extendedProperties.latestVersion)
| join kind=leftouter(
	Resources
	| where type == 'microsoft.hybridcompute/machines'
	| project
		machineId = toupper(id),
		status = tostring (properties.status)
	) on $left.JoinId == $right.machineId
| where status != 'Expired'
| summarize by id, machineName, agentVersion, expectedVersion
| order by tolower(machineName) asc
az graph query -q "AdvisorResources | where type == 'microsoft.advisor/recommendations' | where properties.category == 'HighAvailability' | where properties.shortDescription.solution == 'Upgrade to the latest version of the Azure Connected Machine agent' | project  id,  JoinId = toupper(properties.resourceMetadata.resourceId),  machineName = tostring(properties.impactedValue),  agentVersion = tostring(properties.extendedProperties.installedVersion),  expectedVersion = tostring(properties.extendedProperties.latestVersion) | join kind=leftouter( Resources | where type == 'microsoft.hybridcompute/machines' | project  machineId = toupper(id),  status = tostring (properties.status) ) on \$left.JoinId == \$right.machineId | where status != 'Expired' | summarize by id, machineName, agentVersion, expectedVersion | order by tolower(machineName) asc"

Centro di Azure per soluzioni SAP

Integrità corrente delle macchine virtuali in Istanza virtuale per SAP

Questa query recupera l'integrità di disponibilità corrente di tutte le macchine virtuali di un sistema SAP in base al SID di un'istanza virtuale per SAP. Sostituire mySubscriptionId con l'ID sottoscrizione e sostituire myResourceId con l'ID risorsa dell'istanza virtuale per SAP.

Resources
| where subscriptionId == 'mySubscriptionId'
| where type startswith 'microsoft.workloads/sapvirtualinstances/'
| where id startswith 'myResourceId'
| mv-expand d = properties.vmDetails
| project VmId = tolower(d.virtualMachineId)
| join kind = inner (
  HealthResources
  | where subscriptionId == 'mySubscriptionId'
  | where type == 'microsoft.resourcehealth/availabilitystatuses'
  | where properties contains 'Microsoft.Compute/virtualMachines'
  | extend VmId = tolower(tostring(properties['targetResourceId']))
  | extend AvailabilityState = tostring(properties['availabilityState']))
on $left.VmId == $right.VmId
| project VmId, todatetime(properties['occurredTime']), AvailabilityState
| project-rename ['Virtual Machine ID'] = VmId, UTCTimeStamp = properties_occurredTime, ['Availability State'] = AvailabilityState
az graph query -q "Resources | where subscriptionId == 'mySubscriptionId' | where type startswith 'microsoft.workloads/sapvirtualinstances/' | where id startswith 'myResourceId' | mv-expand d = properties.vmDetails | project VmId = tolower(d.virtualMachineId) | join kind = inner (HealthResources | where subscriptionId == 'mySubscriptionId' | where type == 'microsoft.resourcehealth/availabilitystatuses' | where properties contains 'Microsoft.Compute/virtualMachines' | extend VmId = tolower(tostring(properties['targetResourceId'])) | extend AvailabilityState = tostring(properties['availabilityState'])) on \$left.VmId == \$right.VmId | project VmId, todatetime(properties['occurredTime']), AvailabilityState | project-rename ['Virtual Machine ID'] = VmId, UTCTimeStamp = properties_occurredTime, ['Availability State'] = AvailabilityState"

Macchine virtuali e annotazioni attualmente non integre in Istanza virtuale per SAP

Questa query recupera l'elenco delle macchine virtuali di un sistema SAP non integre e corrispondenti in base al SID di un'istanza virtuale per SAP. Sostituire mySubscriptionId con l'ID sottoscrizione e sostituire myResourceId con l'ID risorsa dell'istanza virtuale per SAP.

HealthResources
| where subscriptionId == 'mySubscriptionId'
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| where properties contains 'Microsoft.Compute/virtualMachines'
| extend VmId = tolower(tostring(properties['targetResourceId']))
| extend AvailabilityState = tostring(properties['availabilityState'])
| where AvailabilityState != 'Available'
| project VmId, todatetime(properties['occurredTime']), AvailabilityState
| join kind = inner (
  HealthResources
  | where subscriptionId == 'mySubscriptionId'
  | where type == 'microsoft.resourcehealth/resourceannotations'
  | where properties contains 'Microsoft.Compute/virtualMachines'
  | extend VmId = tolower(tostring(properties['targetResourceId']))) on $left.VmId == $right.VmId
  | join kind = inner (Resources
  | where subscriptionId == 'mySubscriptionId'
  | where type startswith 'microsoft.workloads/sapvirtualinstances/'
  | where id startswith 'myResourceId'
  | mv-expand d = properties.vmDetails
  | project VmId = tolower(d.virtualMachineId))
on $left.VmId1 == $right.VmId
| extend AnnotationName = tostring(properties['annotationName']), ImpactType = tostring(properties['impactType']), Context = tostring(properties['context']), Summary = tostring(properties['summary']), Reason = tostring(properties['reason']), OccurredTime = todatetime(properties['occurredTime'])
| project VmId, OccurredTime, AvailabilityState, AnnotationName, ImpactType, Context, Summary, Reason
| project-rename ['Virtual Machine ID'] = VmId, ['Time Since Not Available'] = OccurredTime, ['Availability State'] = AvailabilityState, ['Annotation Name'] = AnnotationName, ['Impact Type'] = ImpactType
az graph query -q "HealthResources | where subscriptionId == 'mySubscriptionId' | where type == 'microsoft.resourcehealth/availabilitystatuses' | where properties contains 'Microsoft.Compute/virtualMachines' | extend VmId = tolower(tostring(properties['targetResourceId'])) | extend AvailabilityState = tostring(properties['availabilityState']) | where AvailabilityState != 'Available' | project VmId, todatetime(properties['occurredTime']), AvailabilityState | join kind = inner (HealthResources | where subscriptionId == 'mySubscriptionId' | where type == 'microsoft.resourcehealth/resourceannotations' | where properties contains 'Microsoft.Compute/virtualMachines' | extend VmId = tolower(tostring(properties['targetResourceId']))) on \$left.VmId == \$right.VmId   | join kind = inner (Resources | where subscriptionId == 'mySubscriptionId' | where type startswith 'microsoft.workloads/sapvirtualinstances/' | where id startswith 'myResourceId' | mv-expand d = properties.vmDetails | project VmId = tolower(d.virtualMachineId)) on \$left.VmId1 == \$right.VmId | extend AnnotationName = tostring(properties['annotationName']), ImpactType = tostring(properties['impactType']), Context = tostring(properties['context']), Summary = tostring(properties['summary']), Reason = tostring(properties['reason']), OccurredTime = todatetime(properties['occurredTime']) | project VmId, OccurredTime, AvailabilityState, AnnotationName, ImpactType, Context, Summary, Reason | project-rename ['Virtual Machine ID'] = VmId, ['Time Since Not Available'] = OccurredTime, ['Availability State'] = AvailabilityState, ['Annotation Name'] = AnnotationName, ['Impact Type'] = ImpactType"

Modifiche all'integrità delle macchine virtuali e delle annotazioni in Istanza virtuale per SAP

Questa query recupera le modifiche cronologiche nell'integrità della disponibilità e le annotazioni corrispondenti di tutte le macchine virtuali di un sistema SAP in base al SID di un'istanza virtuale per SAP. Sostituire mySubscriptionId con l'ID sottoscrizione e sostituire myResourceId con l'ID risorsa dell'istanza virtuale per SAP.

Resources
| where subscriptionId == 'mySubscriptionId'
| where type startswith 'microsoft.workloads/sapvirtualinstances/'
| where id startswith 'myResourceId'
| mv-expand d = properties.vmDetails
| project VmId = tolower(d.virtualMachineId)
| join kind = leftouter (
  HealthResourceChanges
  | where subscriptionId == 'mySubscriptionId'
  | where id !has '/virtualMachineScaleSets/'
  | where id has '/virtualMachines/'
  | extend timestamp = todatetime(properties.changeAttributes.timestamp)
  | extend VmId = tolower(tostring(split(id, '/providers/Microsoft.ResourceHealth/')[0]))
  | where properties has 'properties.availabilityState' or properties has 'properties.annotationName'
  | extend HealthChangeType = iff(properties has 'properties.availabilityState', 'Availability', 'Annotation')
  | extend ChangeType = tostring(properties.changeType)
  | where ChangeType == 'Update'  or ChangeType == 'Delete')
on $left.VmId == $right.VmId
| extend Changes = parse_json(tostring(properties.changes))
| extend AvailabilityStateJson = parse_json(tostring(Changes['properties.availabilityState']))
| extend AnnotationNameJson = parse_json(tostring(Changes['properties.annotationName']))
| extend AnnotationSummary = parse_json(tostring(Changes['properties.summary']))
| extend AnnotationReason = parse_json(tostring(Changes['properties.reason']))
| extend AnnotationImpactType = parse_json(tostring(Changes['properties.impactType']))
| extend AnnotationContext = parse_json(tostring(Changes['properties.context']))
| extend AnnotationCategory = parse_json(tostring(Changes['properties.category']))
| extend AvailabilityStatePreviousValue = tostring(AvailabilityStateJson.previousValue)
| extend AvailabilityStateCurrentValue = tostring(AvailabilityStateJson.newValue)
| extend AnnotationNamePreviousValue = tostring(AnnotationNameJson.previousValue)
| extend AnnotationNameCurrentValue = tostring(AnnotationNameJson.newValue)
| extend AnnotationSummaryCurrentValue = tostring(AnnotationSummary.newValue)
| extend AnnotationReasonCurrentValue = tostring(AnnotationReason.newValue)
| extend AnnotationImpactTypeCurrentValue = tostring(AnnotationImpactType.newValue)
| extend AnnotationContextCurrentValue = tostring(AnnotationContext.newValue)
| extend AnnotationCategoryCurrentValue = tostring(AnnotationCategory.newValue)
| project id = VmId, timestamp, ChangeType, AvailabilityStateCurrentValue, AnnotationNameCurrentValue, AnnotationSummaryCurrentValue, AnnotationReasonCurrentValue, AnnotationImpactTypeCurrentValue, AnnotationContextCurrentValue, AnnotationCategoryCurrentValue, Changes
| order by id, timestamp asc
| project-rename ['Virtual Machine ID'] = id, UTCTimeStamp = timestamp, ['Change Type'] = ChangeType, ['Availability State'] = AvailabilityStateCurrentValue, ['Summary'] = AnnotationSummaryCurrentValue, ['Reason'] = AnnotationReasonCurrentValue, ['Impact Type'] = AnnotationImpactTypeCurrentValue, Category = AnnotationCategoryCurrentValue, Context = AnnotationContextCurrentValue
az graph query -q "Resources | where subscriptionId == 'mySubscriptionId' | where type startswith 'microsoft.workloads/sapvirtualinstances/' | where id startswith 'myResourceId' | mv-expand d = properties.vmDetails | project VmId = tolower(d.virtualMachineId) | join kind = leftouter (HealthResourceChanges | where subscriptionId == 'mySubscriptionId' | where id !has '/virtualMachineScaleSets/' | where id has '/virtualMachines/' | extend timestamp = todatetime(properties.changeAttributes.timestamp) | extend VmId = tolower(tostring(split(id, '/providers/Microsoft.ResourceHealth/')[0])) | where properties has 'properties.availabilityState' or properties has 'properties.annotationName' | extend HealthChangeType = iff(properties has 'properties.availabilityState', 'Availability', 'Annotation') | extend ChangeType = tostring(properties.changeType) | where ChangeType == 'Update' or ChangeType == 'Delete') on \$left.VmId == \$right.VmId | extend Changes = parse_json(tostring(properties.changes)) | extend AvailabilityStateJson = parse_json(tostring(Changes['properties.availabilityState'])) | extend AnnotationNameJson = parse_json(tostring(Changes['properties.annotationName'])) | extend AnnotationSummary = parse_json(tostring(Changes['properties.summary'])) | extend AnnotationReason = parse_json(tostring(Changes['properties.reason'])) | extend AnnotationImpactType = parse_json(tostring(Changes['properties.impactType'])) | extend AnnotationContext = parse_json(tostring(Changes['properties.context'])) | extend AnnotationCategory = parse_json(tostring(Changes['properties.category'])) | extend AvailabilityStatePreviousValue = tostring(AvailabilityStateJson.previousValue) | extend AvailabilityStateCurrentValue = tostring(AvailabilityStateJson.newValue) | extend AnnotationNamePreviousValue = tostring(AnnotationNameJson.previousValue) | extend AnnotationNameCurrentValue = tostring(AnnotationNameJson.newValue) | extend AnnotationSummaryCurrentValue = tostring(AnnotationSummary.newValue) | extend AnnotationReasonCurrentValue = tostring(AnnotationReason.newValue) | extend AnnotationImpactTypeCurrentValue = tostring(AnnotationImpactType.newValue) | extend AnnotationContextCurrentValue = tostring(AnnotationContext.newValue) | extend AnnotationCategoryCurrentValue = tostring(AnnotationCategory.newValue) | project id = VmId, timestamp, ChangeType, AvailabilityStateCurrentValue, AnnotationNameCurrentValue, AnnotationSummaryCurrentValue, AnnotationReasonCurrentValue, AnnotationImpactTypeCurrentValue, AnnotationContextCurrentValue, AnnotationCategoryCurrentValue, Changes | order by id, timestamp asc | project-rename ['Virtual Machine ID'] = id, UTCTimeStamp = timestamp, ['Change Type'] = ChangeType, ['Availability State'] = AvailabilityStateCurrentValue, ['Summary'] = AnnotationSummaryCurrentValue, ['Reason'] = AnnotationReasonCurrentValue, ['Impact Type'] = AnnotationImpactTypeCurrentValue, Category = AnnotationCategoryCurrentValue, Context = AnnotationContextCurrentValue"

Registro Azure Container

Elencare i risultati della valutazione della vulnerabilità del Registro Container

Restituisce tutte le vulnerabilità rilevate nelle immagini del contenitore. Microsoft Defender per contenitori deve essere abilitato per visualizzare questi risultati di sicurezza.

SecurityResources
| where type == 'microsoft.security/assessments'
| where properties.displayName contains 'Container registry images should have vulnerability findings resolved'
| summarize by assessmentKey=name //the ID of the assessment
| join kind=inner (
	securityresources
	| where type == 'microsoft.security/assessments/subassessments'
	| extend assessmentKey = extract('.*assessments/(.+?)/.*',1,  id)
) on assessmentKey
| project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId
| extend description = properties.description,
	displayName = properties.displayName,
	resourceId = properties.resourceDetails.id,
	resourceSource = properties.resourceDetails.source,
	category = properties.category,
	severity = properties.status.severity,
	code = properties.status.code,
	timeGenerated = properties.timeGenerated,
	remediation = properties.remediation,
	impact = properties.impact,
	vulnId = properties.id,
	additionalData = properties.additionalData
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | where properties.displayName contains 'Container registry images should have vulnerability findings resolved' | summarize by assessmentKey=name //the ID of the assessment | join kind=inner ( securityresources | where type == 'microsoft.security/assessments/subassessments' | extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id) ) on assessmentKey | project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId | extend description = properties.description, displayName = properties.displayName, resourceId = properties.resourceDetails.id, resourceSource = properties.resourceDetails.source, category = properties.category, severity = properties.status.severity, code = properties.status.code, timeGenerated = properties.timeGenerated, remediation = properties.remediation, impact = properties.impact, vulnId = properties.id, additionalData = properties.additionalData"

Azure Cosmos DB

Elencare Azure Cosmos DB con specifiche posizioni di scrittura

La query seguente si limita alle risorse di Azure Cosmos DB, usa mv-expand per espandere il contenitore di proprietà per properties.writeLocations, quindi i campi specifici del progetto, e per limitare ulteriormente i risultati ai valori di properties.writeLocations.locationName che corrispondono a 'Stati Uniti orientali' o 'Stati Uniti occidentali'.

Resources
| where type =~ 'microsoft.documentdb/databaseaccounts'
| project id, name, writeLocations = (properties.writeLocations)
| mv-expand writeLocations
| project id, name, writeLocation = tostring(writeLocations.locationName)
| where writeLocation in ('East US', 'West US')
| summarize by id, name
az graph query -q "Resources | where type =~ 'microsoft.documentdb/databaseaccounts' | project id, name, writeLocations = (properties.writeLocations) | mv-expand writeLocations | project id, name, writeLocation = tostring(writeLocations.locationName) | where writeLocation in ('East US', 'West US') | summarize by id, name"

Azure Key Vault

Contare le risorse dell'insieme di credenziali delle chiavi

Questa query usa count invece di summarize per contare il numero di record restituiti. Nel conteggio sono inclusi solo gli insiemi di credenziali delle chiavi.

Resources
| where type =~ 'microsoft.keyvault/vaults'
| count
az graph query -q "Resources | where type =~ 'microsoft.keyvault/vaults' | count"

Insieme di credenziali delle chiavi con il nome della sottoscrizione

La query seguente illustra un uso complesso di join con kind come leftouter. La query limita la tabella aggiunta alle risorse della sottoscrizione e usa project per includere solo il campo subscriptionId originale e il campo name rinominato in SubName. La ridenominazione del campo evita che join lo aggiunga come name1, perché il campo esiste già in resources. La tabella originale viene filtrata con where e l'elemento project seguente include colonne di entrambe le tabelle. Il risultato della query è che tutti gli insiemi di credenziali delle chiavi visualizzano il tipo, il nome dell'insieme di credenziali delle chiavi e il nome della sottoscrizione in cui è incluso.

Resources
| join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId
| where type == 'microsoft.keyvault/vaults'
| project type, name, SubName
az graph query -q "Resources | join kind=leftouter (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId | where type == 'microsoft.keyvault/vaults' | project type, name, SubName"

Monitoraggio di Azure

Visualizzare gli avvisi recenti di Monitoraggio di Azure

Questa query di esempio ottiene tutti gli avvisi di Monitoraggio di Azure generati nelle ultime 12 ore ed estrae le proprietà di uso comune.

alertsmanagementresources
| where properties.essentials.startDateTime > ago(12h)
| project
  alertId = id,
  name,
  monitorCondition = tostring(properties.essentials.monitorCondition),
  severity = tostring(properties.essentials.severity),
  monitorService = tostring(properties.essentials.monitorService),
  alertState = tostring(properties.essentials.alertState),
  targetResourceType = tostring(properties.essentials.targetResourceType),
  targetResource = tostring(properties.essentials.targetResource),
  subscriptionId,
  startDateTime = todatetime(properties.essentials.startDateTime),
  lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime),
  dimensions = properties.context.context.condition.allOf[0].dimensions, properties
az graph query -q "alertsmanagementresources | where properties.essentials.startDateTime > ago(12h) | project   alertId = id,   name,   monitorCondition = tostring(properties.essentials.monitorCondition),   severity = tostring(properties.essentials.severity),   monitorService = tostring(properties.essentials.monitorService),   alertState = tostring(properties.essentials.alertState),   targetResourceType = tostring(properties.essentials.targetResourceType),   targetResource = tostring(properties.essentials.targetResource),   subscriptionId,   startDateTime = todatetime(properties.essentials.startDateTime),   lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime),   dimensions = properties.context.context.condition.allOf[0].dimensions, properties"

Visualizzare gli avvisi recenti di Monitoraggio di Azure arricchiti con i tag delle risorse

Questa query di esempio ottiene tutti gli avvisi di Monitoraggio di Azure generati nelle ultime 12 ore, estrae le proprietà di uso comune e aggiunge i tag della risorsa di destinazione.

alertsmanagementresources
| where properties.essentials.startDateTime > ago(12h)
| where tostring(properties.essentials.monitorService) <> "ActivityLog Administrative"
| project // converting extracted fields to string / datetime to allow grouping
  alertId = id,
  name,
  monitorCondition = tostring(properties.essentials.monitorCondition),
  severity = tostring(properties.essentials.severity),
  monitorService = tostring(properties.essentials.monitorService),
  alertState = tostring(properties.essentials.alertState),
  targetResourceType = tostring(properties.essentials.targetResourceType),
  targetResource = tostring(properties.essentials.targetResource),
  subscriptionId,
  startDateTime = todatetime(properties.essentials.startDateTime),
  lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime),
  dimensions = properties.context.context.condition.allOf[0].dimensions, // usefor metric alerts and log search alerts
  properties
| extend targetResource = tolower(targetResource)
| join kind=leftouter
  ( resources | project targetResource = tolower(id), targetResourceTags = tags) on targetResource
| project-away targetResource1
az graph query -q "alertsmanagementresources | where properties.essentials.startDateTime > ago(12h) | where tostring(properties.essentials.monitorService) <> "ActivityLog Administrative" | project // converting extracted fields to string / datetime to allow grouping   alertId = id,   name,   monitorCondition = tostring(properties.essentials.monitorCondition),   severity = tostring(properties.essentials.severity),   monitorService = tostring(properties.essentials.monitorService),   alertState = tostring(properties.essentials.alertState),   targetResourceType = tostring(properties.essentials.targetResourceType),   targetResource = tostring(properties.essentials.targetResource),   subscriptionId,   startDateTime = todatetime(properties.essentials.startDateTime),   lastModifiedDateTime = todatetime(properties.essentials.lastModifiedDateTime),   dimensions = properties.context.context.condition.allOf[0].dimensions, // usefor metric alerts and log search alerts   properties | extend targetResource = tolower(targetResource) | join kind=leftouter   ( resources | project targetResource = tolower(id), targetResourceTags = tags) on targetResource | project-away targetResource1"

Elencare tutti i cluster Kubernetes abilitati per Azure Arc con l'estensione Monitoraggio di Azure

Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc in cui è installata l'estensione Monitoraggio di Azure.

KubernetesConfigurationResources
| where type == 'microsoft.kubernetesconfiguration/extensions'
| where properties.ExtensionType  == 'microsoft.azuremonitor.containers'
| parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' *
| project connectedClusterId
az graph query -q "KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse id with connectedClusterId '/providers/Microsoft.KubernetesConfiguration/Extensions' * | project connectedClusterId"

Elencare tutti i cluster Kubernetes abilitati per Azure Arc senza l'estensione Monitoraggio di Azure

Restituisce l'ID cluster connesso di ogni cluster Kubernetes abilitato per Azure Arc mancante nell'estensione Monitoraggio di Azure.

Resources
| where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId
| join kind = leftouter
	(KubernetesConfigurationResources
	| where type == 'microsoft.kubernetesconfiguration/extensions'
	| where properties.ExtensionType  == 'microsoft.azuremonitor.containers'
	| parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' *
	| project connectedClusterId
)  on connectedClusterId
| where connectedClusterId1 == ''
| project connectedClusterId
az graph query -q "Resources | where type =~ 'Microsoft.Kubernetes/connectedClusters' | extend connectedClusterId = tolower(id) | project connectedClusterId | join kind = leftouter (KubernetesConfigurationResources | where type == 'microsoft.kubernetesconfiguration/extensions' | where properties.ExtensionType == 'microsoft.azuremonitor.containers' | parse tolower(id) with connectedClusterId '/providers/microsoft.kubernetesconfiguration/extensions' * | project connectedClusterId ) on connectedClusterId | where connectedClusterId1 == '' | project connectedClusterId"

Restituisce tutti gli avvisi di Monitoraggio di Azure in una sottoscrizione nell'ultimo giorno

{
  "subscriptions": [
    <subscriptionId>
  ],
  "query": "alertsmanagementresources | where properties.essentials.lastModifiedDateTime > ago(1d) | project alertInstanceId = id, parentRuleId = tolower(tostring(properties['essentials']['alertRule'])), sourceId = properties['essentials']['sourceCreatedId'], alertName = name, severity = properties.essentials.severity, status = properties.essentials.monitorCondition, state = properties.essentials.alertState, affectedResource = properties.essentials.targetResourceName, monitorService = properties.essentials.monitorService, signalType = properties.essentials.signalType, firedTime = properties['essentials']['startDateTime'], lastModifiedDate = properties.essentials.lastModifiedDateTime, lastModifiedBy = properties.essentials.lastModifiedUserName"
}

Contare le regole di raccolta dati di Monitoraggio di Azure per sottoscrizione e gruppo di risorse

Questa query raggruppa le regole di raccolta dati di Monitoraggio di Azure per sottoscrizione e gruppo di risorse.

resources
| where type == 'microsoft.insights/datacollectionrules'
| summarize dcrCount = count() by subscriptionId, resourceGroup, location
| sort by dcrCount desc
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | summarize dcrCount = count() by subscriptionId, resourceGroup, location | sort by dcrCount desc"

Contare le regole di raccolta dei dati di Monitoraggio di Azure in base alla posizione

Questa query raggruppa le regole di raccolta dati di Monitoraggio di Azure in base alla posizione.

resources
| where type == 'microsoft.insights/datacollectionrules'
| summarize dcrCount=count() by location
| sort by dcrCount desc
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | summarize dcrCount=count() by location | sort by dcrCount desc"

Elencare le regole di raccolta dati di Monitoraggio di Azure con l'area di lavoro Log Analytics come destinazione

Ottenere l'elenco delle aree di lavoro Log Analytics e per ognuna delle aree di lavoro, elencare le regole di raccolta dati che specificano l'area di lavoro come una delle destinazioni.

resources
| where type == 'microsoft.insights/datacollectionrules'
| extend destinations = properties['destinations']
| extend logAnalyticsWorkspaces = destinations['logAnalytics']
| where isnotnull(logAnalyticsWorkspaces)
| mv-expand logAnalyticsWorkspace = logAnalyticsWorkspaces
| extend logAnalyticsWorkspaceResourceId = tolower(tostring(logAnalyticsWorkspace['workspaceResourceId']))
| summarize dcrList = make_list(id), dcrCount = count() by logAnalyticsWorkspaceResourceId
| sort by dcrCount desc
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | extend destinations = properties['destinations'] | extend logAnalyticsWorkspaces = destinations['logAnalytics'] | where isnotnull(logAnalyticsWorkspaces) | mv-expand logAnalyticsWorkspace = logAnalyticsWorkspaces | extend logAnalyticsWorkspaceResourceId = tolower(tostring(logAnalyticsWorkspace['workspaceResourceId'])) | summarize dcrList = make_list(id), dcrCount = count() by logAnalyticsWorkspaceResourceId | sort by dcrCount desc"

Elencare le regole di raccolta dati che usano metriche di Monitoraggio di Azure come una delle relative destinazioni

Questa query elenca le regole di raccolta dati che usano metriche di Monitoraggio di Azure come una delle relative destinazioni.

resources
| where type == 'microsoft.insights/datacollectionrules'
| extend destinations = properties['destinations']
| extend azureMonitorMetrics = destinations['azureMonitorMetrics']
| where isnotnull(azureMonitorMetrics)
| project-away destinations, azureMonitorMetrics
az graph query -q "resources | where type == 'microsoft.insights/datacollectionrules' | extend destinations = properties['destinations'] | extend azureMonitorMetrics = destinations['azureMonitorMetrics'] | where isnotnull(azureMonitorMetrics) | project-away destinations, azureMonitorMetrics"

Elencare le macchine virtuali con associazioni di regole di raccolta dati

Questa query elenca le macchine virtuali con associazioni di regole di raccolta dati. Per ogni macchina virtuale, elenca le regole di raccolta dati associate.

insightsresources
| where type == 'microsoft.insights/datacollectionruleassociations'
| where id contains 'microsoft.compute/virtualmachines/'
| project id = trim_start('/', tolower(id)), properties
| extend idComponents = split(id, '/')
| extend subscription = tolower(tostring(idComponents[1])), resourceGroup = tolower(tostring(idComponents[3])), vmName = tolower(tostring(idComponents[7]))
| extend dcrId = properties['dataCollectionRuleId']
| where isnotnull(dcrId)
| extend dcrId = tostring(dcrId)
| summarize dcrList = make_list(dcrId), dcrCount = count() by subscription, resourceGroup, vmName
| sort by dcrCount desc
az graph query -q "insightsresources | where type == 'microsoft.insights/datacollectionruleassociations' | where id contains 'microsoft.compute/virtualmachines/' | project id = trim_start('/', tolower(id)), properties | extend idComponents = split(id, '/') | extend subscription = tolower(tostring(idComponents[1])), resourceGroup = tolower(tostring(idComponents[3])), vmName = tolower(tostring(idComponents[7])) | extend dcrId = properties['dataCollectionRuleId'] | where isnotnull(dcrId) | extend dcrId = tostring(dcrId) | summarize dcrList = make_list(dcrId), dcrCount = count() by subscription, resourceGroup, vmName | sort by dcrCount desc"

Stazione di terra di Azure Orbital

Elencare i prossimi contatti

Questa query consente ai clienti di tenere traccia di tutti i prossimi contatti ordinati in base all'ora di inizio della prenotazione.

OrbitalResources
| where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now()
| sort by todatetime(properties.reservationStartTime)
| extend Contact_Profile = tostring(split(properties.contactProfile.id, "/")[-1])
| extend Spacecraft = tostring(split(id, "/")[-3])
| project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Status=properties.status, Provisioning_Status=properties.provisioningState
az graph query -q "OrbitalResources | where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now() | sort by todatetime(properties.reservationStartTime) | extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1]) | extend Spacecraft = tostring(split(id, '/')[-3]) | project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Status=properties.status, Provisioning_Status=properties.provisioningState"

Elencare i contatti degli ultimi giorni 'x' sulla stazione di terra specificata

Questa query consente ai clienti di tenere traccia di tutti i contatti degli ultimi x giorni ordinati in base all'ora di inizio della prenotazione per una stazione di terra specificata. La funzione now(-1d) specifica il numero di giorni precedenti.

OrbitalResources
| where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now(-1d) and properties.groundStationName == 'Microsoft_Gavle'
| sort by todatetime(properties.reservationStartTime)
| extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1])
| extend Spacecraft = tostring(split(id, '/')[-3])
| project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState
az graph query -q "OrbitalResources | where type == 'microsoft.orbital/spacecrafts/contacts' and todatetime(properties.reservationStartTime) >= now(-1d) and properties.groundStationName == 'Microsoft_Gavle' | sort by todatetime(properties.reservationStartTime) | extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1]) | extend Spacecraft = tostring(split(id, '/')[-3]) | project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState"

Elencare i contatti degli ultimi giorni 'x' nel profilo di contatto specificato

Questa query consente ai clienti di tenere traccia di tutti i contatti degli ultimi x giorni ordinati in base all'ora di inizio della prenotazione per un profilo di contatto specificato. La funzione now(-1d) specifica il numero di giorni precedenti.

OrbitalResources
| where type == 'microsoft.orbital/spacecrafts/contacts'
| extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1])
| where todatetime(properties.reservationStartTime) >= now(-1d) and Contact_Profile == 'test-CP'
| sort by todatetime(properties.reservationStartTime)
| extend Spacecraft = tostring(split(id, '/')[-3])
| project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState
az graph query -q "OrbitalResources | where type == 'microsoft.orbital/spacecrafts/contacts' | extend Contact_Profile = tostring(split(properties.contactProfile.id, '/')[-1]) | where todatetime(properties.reservationStartTime) >= now(-1d) and Contact_Profile == 'test-CP' | sort by todatetime(properties.reservationStartTime) | extend Spacecraft = tostring(split(id, '/')[-3]) | project Contact = tostring(name), Groundstation = tostring(properties.groundStationName), Spacecraft, Contact_Profile, Reservation_Start_Time = todatetime(properties.reservationStartTime), Reservation_End_Time = todatetime(properties.reservationEndTime), Status=properties.status, Provisioning_Status=properties.provisioningState"

Criteri di Azure

Conformità in base all'assegnazione dei criteri

Fornisce lo stato di conformità, la percentuale di conformità e il numero di risorse per ogni assegnazione Criteri di Azure.

PolicyResources
| where type =~ 'Microsoft.PolicyInsights/PolicyStates'
| extend complianceState = tostring(properties.complianceState)
| extend
	resourceId = tostring(properties.resourceId),
	policyAssignmentId = tostring(properties.policyAssignmentId),
	policyAssignmentScope = tostring(properties.policyAssignmentScope),
	policyAssignmentName = tostring(properties.policyAssignmentName),
	policyDefinitionId = tostring(properties.policyDefinitionId),
	policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId),
	stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0)))))
| summarize max(stateWeight) by resourceId, policyAssignmentId, policyAssignmentScope, policyAssignmentName
| summarize counts = count() by policyAssignmentId, policyAssignmentScope, max_stateWeight, policyAssignmentName
| summarize overallStateWeight = max(max_stateWeight),
nonCompliantCount = sumif(counts, max_stateWeight == 300),
compliantCount = sumif(counts, max_stateWeight == 200),
conflictCount = sumif(counts, max_stateWeight == 100),
exemptCount = sumif(counts, max_stateWeight == 50) by policyAssignmentId, policyAssignmentScope, policyAssignmentName
| extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount)
| extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources)
| project policyAssignmentName, scope = policyAssignmentScope,
complianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))),
compliancePercentage,
compliantCount,
nonCompliantCount,
conflictCount,
exemptCount
az graph query -q "PolicyResources | where type =~ 'Microsoft.PolicyInsights/PolicyStates' | extend complianceState = tostring(properties.complianceState) | extend resourceId = tostring(properties.resourceId), policyAssignmentId = tostring(properties.policyAssignmentId), policyAssignmentScope = tostring(properties.policyAssignmentScope), policyAssignmentName = tostring(properties.policyAssignmentName), policyDefinitionId = tostring(properties.policyDefinitionId), policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId), stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0))))) | summarize max(stateWeight) by resourceId, policyAssignmentId, policyAssignmentScope, policyAssignmentName | summarize counts = count() by policyAssignmentId, policyAssignmentScope, max_stateWeight, policyAssignmentName | summarize overallStateWeight = max(max_stateWeight), nonCompliantCount = sumif(counts, max_stateWeight == 300), compliantCount = sumif(counts, max_stateWeight == 200), conflictCount = sumif(counts, max_stateWeight == 100), exemptCount = sumif(counts, max_stateWeight == 50) by policyAssignmentId, policyAssignmentScope, policyAssignmentName | extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount) | extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources) | project policyAssignmentName, scope = policyAssignmentScope, complianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))), compliancePercentage, compliantCount, nonCompliantCount, conflictCount, exemptCount"

Conformità per tipo di risorsa

Fornisce lo stato di conformità, la percentuale di conformità e il numero di risorse per ogni tipo di risorsa.

PolicyResources
| where type =~ 'Microsoft.PolicyInsights/PolicyStates'
| extend complianceState = tostring(properties.complianceState)
| extend
	resourceId = tostring(properties.resourceId),
	resourceType = tolower(tostring(properties.resourceType)),
	policyAssignmentId = tostring(properties.policyAssignmentId),
	policyDefinitionId = tostring(properties.policyDefinitionId),
	policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId),
	stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0)))))
| summarize max(stateWeight) by resourceId, resourceType
| summarize counts = count() by resourceType, max_stateWeight
| summarize overallStateWeight = max(max_stateWeight),
nonCompliantCount = sumif(counts, max_stateWeight == 300),
compliantCount = sumif(counts, max_stateWeight == 200),
conflictCount = sumif(counts, max_stateWeight == 100),
exemptCount = sumif(counts, max_stateWeight == 50) by resourceType
| extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount)
| extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources)
| project resourceType,
overAllComplianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))),
compliancePercentage,
compliantCount,
nonCompliantCount,
conflictCount,
exemptCount
az graph query -q "PolicyResources | where type =~ 'Microsoft.PolicyInsights/PolicyStates' | extend complianceState = tostring(properties.complianceState) | extend resourceId = tostring(properties.resourceId), resourceType = tolower(tostring(properties.resourceType)), policyAssignmentId = tostring(properties.policyAssignmentId), policyDefinitionId = tostring(properties.policyDefinitionId), policyDefinitionReferenceId = tostring(properties.policyDefinitionReferenceId), stateWeight = iff(complianceState == 'NonCompliant', int(300), iff(complianceState == 'Compliant', int(200), iff(complianceState == 'Conflict', int(100), iff(complianceState == 'Exempt', int(50), int(0))))) | summarize max(stateWeight) by resourceId, resourceType | summarize counts = count() by resourceType, max_stateWeight | summarize overallStateWeight = max(max_stateWeight), nonCompliantCount = sumif(counts, max_stateWeight == 300), compliantCount = sumif(counts, max_stateWeight == 200), conflictCount = sumif(counts, max_stateWeight == 100), exemptCount = sumif(counts, max_stateWeight == 50) by resourceType | extend totalResources = todouble(nonCompliantCount + compliantCount + conflictCount + exemptCount) | extend compliancePercentage = iff(totalResources == 0, todouble(100), 100 * todouble(compliantCount + exemptCount) / totalResources) | project resourceType, overAllComplianceState = iff(overallStateWeight == 300, 'noncompliant', iff(overallStateWeight == 200, 'compliant', iff(overallStateWeight == 100, 'conflict', iff(overallStateWeight == 50, 'exempt', 'notstarted')))), compliancePercentage, compliantCount, nonCompliantCount, conflictCount, exemptCount"

Elencare tutte le risorse non conformi

Fornisce un elenco di tutti i tipi di risorse in NonCompliant uno stato.

PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| where properties.complianceState == 'NonCompliant'
| extend NonCompliantResourceId = properties.resourceId, PolicyAssignmentName = properties.policyAssignmentName
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | where properties.complianceState == 'NonCompliant' | extend NonCompliantResourceId = properties.resourceId, PolicyAssignmentName = properties.policyAssignmentName"

Riepilogare la conformità delle risorse in base allo stato

Dettagli sul numero di risorse in ogni stato di conformità.

PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| extend complianceState = tostring(properties.complianceState)
| summarize count() by complianceState
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | extend complianceState = tostring(properties.complianceState) | summarize count() by complianceState"

Riepilogare la conformità delle risorse in base allo stato per località

Dettagli sul numero di risorse in ogni stato di conformità per ogni posizione.

PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| extend complianceState = tostring(properties.complianceState)
| extend resourceLocation = tostring(properties.resourceLocation)
| summarize count() by resourceLocation, complianceState
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | extend complianceState = tostring(properties.complianceState) | extend resourceLocation = tostring(properties.resourceLocation) | summarize count() by resourceLocation, complianceState"

Esenzioni dei criteri per assegnazione

Elenca il numero di esenzioni per ogni assegnazione.

PolicyResources
| where type == 'microsoft.authorization/policyexemptions'
| summarize count() by tostring(properties.policyAssignmentId)

Per altre informazioni sull'uso degli ambiti con l'interfaccia della riga di comando di Azure o Azure PowerShell, vedere Contare le risorse di Azure.

Usare il --management-groups parametro con un ID gruppo di gestione di Azure o un ID tenant. In questo esempio la tenantid variabile archivia l'ID tenant.

tenantid="$(az account show --query tenantId --output tsv)"
az graph query -q "policyresources | where type == 'microsoft.authorization/policyexemptions' | summarize count() by tostring(properties.policyAssignmentId)" --management-groups $tenantid

Esenzioni dei criteri che scadono entro 90 giorni

Elenca il nome e la data di scadenza.

PolicyResources
| where type == 'microsoft.authorization/policyexemptions'
| extend expiresOnC = todatetime(properties.expiresOn)
| where isnotnull(expiresOnC)
| where expiresOnC >= now() and expiresOnC < now(+90d)
| project name, expiresOnC
az graph query -q "policyresources | where type == 'microsoft.authorization/policyexemptions' | extend expiresOnC = todatetime(properties.expiresOn) | where isnotnull(expiresOnC) | where expiresOnC >= now() and expiresOnC < now(+90d) | project name, expiresOnC"

Configurazione guest di Criteri di Azure

Conteggio dei computer nell'ambito dei criteri di configurazione guest

Visualizza il conteggio delle macchine virtuali di Azure e dei server connessi Arc nell'ambito per le assegnazioni di configurazione guest Criteri di Azure.

GuestConfigurationResources
| where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments'
| extend vmid = split(properties.targetResourceId,'/')
| mvexpand properties.latestAssignmentReport.resources
| where properties_latestAssignmentReport_resources.resourceId != 'Invalid assignment package.'
| project machine = tostring(vmid[(-1)]),type = tostring(vmid[(-3)])
| distinct machine, type
| summarize count() by type
az graph query -q "GuestConfigurationResources | where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments' | extend vmid = split(properties.targetResourceId,'/') | mvexpand properties.latestAssignmentReport.resources | where properties_latestAssignmentReport_resources.resourceId != 'Invalid assignment package.' | project machine = tostring(vmid[(-1)]),type = tostring(vmid[(-3)]) | distinct machine, type | summarize count() by type"

Numero di assegnazioni di configurazione guest non conformi

Visualizza un conteggio di computer non conformi per ogni motivo di assegnazione della configurazione guest. Limita i risultati ai primi 100 per le prestazioni.

GuestConfigurationResources
| where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments'
| project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| project id, vmid, name, status, resource = tostring(resources.resourceId), reason = reasons.phrase
| summarize count() by resource, name
| order by count_
| limit 100
az graph query -q "GuestConfigurationResources | where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments' | project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | project id, vmid, name, status, resource = tostring(resources.resourceId), reason = reasons.phrase | summarize count() by resource, name | order by count_ | limit 100"

Trovare tutti i motivi per cui un computer non è conforme per le assegnazioni di configurazione guest

Visualizzare tutti i motivi di assegnazione della configurazione guest per un computer specifico. Rimuovere la prima clausola where per includere anche i controlli in cui il computer è conforme.

GuestConfigurationResources
| where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments'
| where properties.complianceStatus == 'NonCompliant'
| project id, name, resources = properties.latestAssignmentReport.resources, machine = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| where machine == 'MACHINENAME'
| project id, machine, name, status, resource = resources.resourceId, reason = reasons.phrase
az graph query -q "GuestConfigurationResources | where type =~ 'microsoft.guestconfiguration/guestconfigurationassignments' | where properties.complianceStatus == 'NonCompliant' | project id, name, resources = properties.latestAssignmentReport.resources, machine = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | where machine == 'MACHINENAME' | project id, machine, name, status, resource = resources.resourceId, reason = reasons.phrase"

Elencare i computer e lo stato del riavvio in sospeso

Fornisce un elenco di computer con i dettagli di configurazione relativi alla presenza di un riavvio in sospeso.

GuestConfigurationResources
| where name in ('WindowsPendingReboot')
| project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/'), status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase
| summarize name = any(name), status = any(status), vmid = any(vmid), resources = make_list_if(resource, isnotnull(resource)), reasons = make_list_if(reason, isnotnull(reason)) by id = tolower(id)
| project id, machine = tostring(vmid[(-1)]), type = tostring(vmid[(-3)]), name, status, reasons
az graph query -q "GuestConfigurationResources | where name in ('WindowsPendingReboot') | project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/'), status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase | summarize name = any(name), status = any(status), vmid = any(vmid), resources = make_list_if(resource, isnotnull(resource)), reasons = make_list_if(reason, isnotnull(reason)) by id = tolower(id) | project id, machine = tostring(vmid[(-1)]), type = tostring(vmid[(-3)]), name, status, reasons"

Elencare i computer che non sono in esecuzione e l'ultimo stato di conformità

Fornisce un elenco di computer non accesi con le assegnazioni di configurazione e l'ultimo stato di conformità segnalato.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| where properties.extended.instanceView.powerState.code != 'PowerState/running'
| project vmName = name, power = properties.extended.instanceView.powerState.code
| join kind = leftouter (GuestConfigurationResources
	| extend vmName = tostring(split(properties.targetResourceId,'/')[(-1)])
	| project vmName, name, compliance = properties.complianceStatus) on vmName | project-away vmName1
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | where properties.extended.instanceView.powerState.code != 'PowerState/running' | project vmName = name, power = properties.extended.instanceView.powerState.code | join kind = leftouter (GuestConfigurationResources | extend vmName = tostring(split(properties.targetResourceId,'/')[(-1)]) | project vmName, name, compliance = properties.complianceStatus) on vmName | project-away vmName1"

Dettagli delle query dei report di assegnazione della configurazione guest

Visualizzare il report dai dettagli del motivo dell'assegnazione della configurazione guest. Nell'esempio seguente la query restituisce solo i risultati in cui il nome dell'assegnazione guest è installed_application_linux e l'output contiene la stringa Chrome per elencare tutti i computer Linux in cui è installato un pacchetto che include il nome Chrome.

GuestConfigurationResources
| where name in ('installed_application_linux')
| project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus)
| extend resources = iff(isnull(resources[0]), dynamic([{}]), resources)
| mvexpand resources
| extend reasons = resources.reasons
| extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons)
| mvexpand reasons
| where reasons.phrase contains 'chrome'
| project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase
az graph query -q "GuestConfigurationResources | where name in ('installed_application_linux') | project id, name, resources = properties.latestAssignmentReport.resources, vmid = split(properties.targetResourceId,'/')[(-1)], status = tostring(properties.complianceStatus) | extend resources = iff(isnull(resources[0]), dynamic([{}]), resources) | mvexpand resources | extend reasons = resources.reasons | extend reasons = iff(isnull(reasons[0]), dynamic([{}]), reasons) | mvexpand reasons | where reasons.phrase contains 'chrome' | project id, vmid, name, status, resource = resources.resourceId, reason = reasons.phrase"

Controllo degli accessi in base al ruolo di Azure

Risolvere i problemi relativi ai limiti del controllo degli accessi in base al ruolo di Azure

La authorizationresources tabella può essere usata per risolvere i problemi relativi al controllo degli accessi in base al ruolo di Azure se si superano i limiti. Per altre informazioni, vedere Risolvere i limiti del controllo degli accessi in base al ruolo di Azure.

Ottenere assegnazioni di ruolo con le proprietà chiave

Fornisce un esempio di assegnazioni di ruolo e alcune delle proprietà pertinenti delle risorse.

authorizationresources
| where type =~ 'microsoft.authorization/roleassignments'
| extend roleDefinitionId = properties.roleDefinitionId
| extend principalType = properties.principalType
| extend principalId = properties.principalId
| extend scope = properties.scope
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roleassignments' | extend roleDefinitionId = properties.roleDefinitionId | extend principalType = properties.principalType | extend principalId = properties.principalId | extend scope = properties.scope | take 5"

Ottenere definizioni di ruolo con proprietà chiave

Fornisce un esempio di definizioni di ruolo e alcune delle risorse pertinenti.

authorizationresources
| where type =~ 'microsoft.authorization/roledefinitions'
| extend assignableScopes = properties.assignableScopes
| extend permissionsList = properties.permissions
| extend isServiceRole = properties.isServiceRole
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roledefinitions' | extend assignableScopes = properties.assignableScopes | extend permissionsList = properties.permissions | extend isServiceRole = properties.isServiceRole | take 5"

Ottenere definizioni di ruolo con azioni

Visualizza un esempio di definizioni di ruolo con un elenco espanso di azioni e non azioni per l'elenco delle autorizzazioni di ogni definizione di ruolo.

authorizationresources
| where type =~ 'microsoft.authorization/roledefinitions'
| extend assignableScopes = properties.assignableScopes
| extend permissionsList = properties.permissions
| extend isServiceRole = properties.isServiceRole
| mv-expand permissionsList
| extend Actions = permissionsList.Actions
| extend notActions = permissionsList.notActions
| extend DataActions = permissionsList.DataActions
| extend notDataActions = permissionsList.notDataActions
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roledefinitions' | extend assignableScopes = properties.assignableScopes | extend permissionsList = properties.permissions | extend isServiceRole = properties.isServiceRole | mv-expand permissionsList | extend Actions = permissionsList.Actions | extend notActions = permissionsList.notActions | extend DataActions = permissionsList.DataActions | extend notDataActions = permissionsList.notDataActions | take 5"

Ottenere definizioni di ruolo con autorizzazioni elencate

Visualizza un riepilogo di Actions e notActions per ogni definizione di ruolo univoca.

authorizationresources
| where type =~ 'microsoft.authorization/roledefinitions'
| extend assignableScopes = properties.assignableScopes
| extend permissionsList = properties.permissions
| extend isServiceRole = properties.isServiceRole
| mv-expand permissionsList
| extend Actions = permissionsList.Actions
| extend notActions = permissionsList.notActions
| extend DataActions = permissionsList.DataActions
| extend notDataActions = permissionsList.notDataActions
| summarize make_set(Actions), make_set(notActions), make_set(DataActions), make_set(notDataActions), any(assignableScopes, isServiceRole) by id
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/roledefinitions' | extend assignableScopes = properties.assignableScopes | extend permissionsList = properties.permissions | extend isServiceRole = properties.isServiceRole | mv-expand permissionsList | extend Actions = permissionsList.Actions | extend notActions = permissionsList.notActions | extend DataActions = permissionsList.DataActions | extend notDataActions = permissionsList.notDataActions | summarize make_set(Actions), make_set(notActions), make_set(DataActions), make_set(notDataActions), any(assignableScopes, isServiceRole) by id"

Ottenere gli amministratori classici con proprietà chiave

Fornisce un esempio di amministratori classici e alcune delle risorse pertinenti.

authorizationresources
| where type =~ 'microsoft.authorization/classicadministrators'
| extend state = properties.adminState
| extend roles = split(properties.role, ';')
| take 5
az graph query -q "authorizationresources | where type =~ 'microsoft.authorization/classicadministrators' | extend state = properties.adminState | extend roles = split(properties.role, ';') | take 5"

Integrità dei servizi di Azure

Impatto della sottoscrizione dell'evento integrità dei servizi attivi

Restituisce tutti gli eventi di integrità dei servizi attivi, inclusi i problemi del servizio, la manutenzione pianificata, gli avvisi di integrità e gli avvisi di sicurezza, raggruppati per tipo di evento e incluso il numero di sottoscrizioni interessate.

ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = tostring(properties.EventType), status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = properties.ImpactMitigationTime
| where eventType == 'ServiceIssue' and status == 'Active'
| summarize count(subscriptionId) by name
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = tostring(properties.EventType), status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = properties.ImpactMitigationTime | where eventType == 'ServiceIssue' and status == 'Active' | summarize count(subscriptionId) by name"

Tutti gli eventi di consulenza sull'integrità attiva

Restituisce tutti gli eventi di integrità del servizio di consulenza sull'integrità attiva in tutte le sottoscrizioni a cui l'utente ha accesso.

ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime))
| where eventType == 'HealthAdvisory' and impactMitigationTime > now()
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where eventType == 'HealthAdvisory' and impactMitigationTime > now()"

Tutti gli eventi di manutenzione pianificata attiva

Restituisce tutti gli eventi di integrità del servizio di manutenzione pianificata attivi in tutte le sottoscrizioni a cui l'utente ha accesso.

ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime))
| where eventType == 'PlannedMaintenance' and impactMitigationTime > now()
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = todatetime(tolong(properties.ImpactMitigationTime)) | where eventType == 'PlannedMaintenance' and impactMitigationTime > now()"

Tutti gli eventi di integrità dei servizi attivi

Restituisce tutti gli eventi di integrità dei servizi attivi in tutte le sottoscrizioni a cui l'utente ha accesso, inclusi problemi di servizio, manutenzione pianificata, avvisi di integrità e avvisi di sicurezza.

ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = properties.ImpactMitigationTime
| where (eventType in ('HealthAdvisory', 'SecurityAdvisory', 'PlannedMaintenance') and impactMitigationTime > now()) or (eventType == 'ServiceIssue' and status == 'Active')
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = properties.ImpactMitigationTime | where (eventType in ('HealthAdvisory', 'SecurityAdvisory', 'PlannedMaintenance') and impactMitigationTime > now()) or (eventType == 'ServiceIssue' and status == 'Active')"

Tutti gli eventi di problema del servizio attivo

Restituisce tutti gli eventi di integrità dei servizi attivi (interruzioni) in tutte le sottoscrizioni a cui l'utente ha accesso.

ServiceHealthResources
| where type =~ 'Microsoft.ResourceHealth/events'
| extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = properties.ImpactMitigationTime
| where eventType == 'ServiceIssue' and status == 'Active'
az graph query -q "ServiceHealthResources | where type =~ 'Microsoft.ResourceHealth/events' | extend eventType = properties.EventType, status = properties.Status, description = properties.Title, trackingId = properties.TrackingId, summary = properties.Summary, priority = properties.Priority, impactStartTime = properties.ImpactStartTime, impactMitigationTime = properties.ImpactMitigationTime | where eventType == 'ServiceIssue' and status == 'Active'"

Azure SQL

Visualizzare i database SQL e i relativi pool elastici

La query seguente usa leftouterjoin per riunire database SQL risorse e i pool elastici correlati, se presenti.

Resources
| where type =~ 'microsoft.sql/servers/databases'
| project databaseId = id, databaseName = name, elasticPoolId = tolower(tostring(properties.elasticPoolId))
| join kind=leftouter (
	Resources
	| where type =~ 'microsoft.sql/servers/elasticpools'
	| project elasticPoolId = tolower(id), elasticPoolName = name, elasticPoolState = properties.state)
	on elasticPoolId
| project-away elasticPoolId1
az graph query -q "Resources | where type =~ 'microsoft.sql/servers/databases' | project databaseId = id, databaseName = name, elasticPoolId = tolower(tostring(properties.elasticPoolId)) | join kind=leftouter ( Resources | where type =~ 'microsoft.sql/servers/elasticpools' | project elasticPoolId = tolower(id), elasticPoolName = name, elasticPoolState = properties.state) on elasticPoolId | project-away elasticPoolId1"

Archiviazione di Azure

Trovare gli account di archiviazione con un tag specifico senza distinzione tra maiuscole e minuscole nel gruppo di risorse

Analogamente alla query "Trovare account di archiviazione con un tag con distinzione tra maiuscole e minuscole nella query del gruppo di risorse", ma quando è necessario cercare un nome di tag senza distinzione tra maiuscole e minuscole e un valore di tag, usare mv-expand con il parametro bagexpansion . Questa query usa una quota maggiore rispetto alla query originale, quindi usare mv-expand solo se necessario.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
	ResourceContainers
	| where type =~ 'microsoft.resources/subscriptions/resourcegroups'
	| mv-expand bagexpansion=array tags
	| where isnotempty(tags)
	| where tags[0] =~ 'key1' and tags[1] =~ 'value1'
	| project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | mv-expand bagexpansion=array tags | where isnotempty(tags) | where tags[0] =~ 'key1' and tags[1] =~ 'value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

Trovare gli account di archiviazione con un tag specifico con distinzione tra maiuscole e minuscole nel gruppo di risorse

La query seguente usa un elemento internojoin per connettere gli account di archiviazione ai gruppi di risorse con un nome di tag e un valore di tag con distinzione tra maiuscole e minuscole specificato.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
	ResourceContainers
	| where type =~ 'microsoft.resources/subscriptions/resourcegroups'
	| where tags['Key1'] =~ 'Value1'
	| project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | where tags['Key1'] =~ 'Value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

Elencare tutti gli account di archiviazione con un valore di tag specifico

Combinare la funzionalità di filtro dell'esempio precedente e filtrare il tipo di risorsa di Azure per la proprietà type. Questa query limita anche la ricerca di tipi specifici di risorse di Azure con un nome di tag e un valore specifici.

Resources
| where type =~ 'Microsoft.Storage/storageAccounts'
| where tags['tag with a space']=='Custom value'
az graph query -q "Resources | where type =~ 'Microsoft.Storage/storageAccounts' | where tags['tag with a space']=='Custom value'"

Mostrare le risorse che contengono archivi

Invece di definire in modo esplicito il tipo da individuare, questa query di esempio troverà tutte le risorse di Azure che contengono (contains) la parola storage.

Resources
| where type contains 'storage' | distinct type
az graph query -q "Resources | where type contains 'storage' | distinct type"

Macchine virtuali di Azure

Conteggio dell'installazione dell'aggiornamento del sistema operativo completata

Restituisce un elenco dello stato delle esecuzioni di installazione degli aggiornamenti del sistema operativo eseguite per i computer negli ultimi 7 giorni.

PatchAssessmentResources
| where type !has 'softwarepatches'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), OS = tostring(prop.osType), installedPatchCount = tostring(prop.installedPatchCount), failedPatchCount = tostring(prop.failedPatchCount), pendingPatchCount = tostring(prop.pendingPatchCount), excludedPatchCount = tostring(prop.excludedPatchCount), notSelectedPatchCount = tostring(prop.notSelectedPatchCount)
| where lTime > ago(7d)
| project lTime, RunID=name,machineName, rgName, resourceType, OS, installedPatchCount, failedPatchCount, pendingPatchCount, excludedPatchCount, notSelectedPatchCount
az graph query -q "PatchAssessmentResources | where type !has 'softwarepatches' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), OS = tostring(prop.osType), installedPatchCount = tostring(prop.installedPatchCount), failedPatchCount = tostring(prop.failedPatchCount), pendingPatchCount = tostring(prop.pendingPatchCount), excludedPatchCount = tostring(prop.excludedPatchCount), notSelectedPatchCount = tostring(prop.notSelectedPatchCount) | where lTime > ago(7d) | project lTime, RunID=name,machineName, rgName, resourceType, OS, installedPatchCount, failedPatchCount, pendingPatchCount, excludedPatchCount, notSelectedPatchCount"

Numero di macchine virtuali per stato di disponibilità e ID sottoscrizione

Restituisce il numero di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate in base al relativo stato di disponibilità in ogni sottoscrizione.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)"

Numero di macchine virtuali per stato di alimentazione

Restituisce il numero di macchine virtuali (tipo Microsoft.Compute/virtualMachines) classificate in base al relativo stato di alimentazione. Per altre informazioni sugli stati di alimentazione, vedere Panoramica degli stati di Power.

Resources
| where type == 'microsoft.compute/virtualmachines'
| summarize count() by PowerState = tostring(properties.extended.instanceView.powerState.code)
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | summarize count() by PowerState = tostring(properties.extended.instanceView.powerState.code)"

Contare le macchine virtuali per tipo di sistema operativo

Continuando dalla query precedente, le risorse sono ancora limitate al tipo Microsoft.Compute/virtualMachines, ma non è più presente il limite sul numero di record restituiti. Invece, sono stati usati summarize e count() per definire come raggruppare e aggregare i valori in base a una proprietà, che in questo esempio è properties.storageProfile.osDisk.osType. Per un esempio dell'aspetto di questa stringa nell'oggetto completo, vedere le informazioni sull'esplorazione delle risorse e l'individuazione delle macchine virtuali.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| summarize count() by tostring(properties.storageProfile.osDisk.osType)
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | summarize count() by tostring(properties.storageProfile.osDisk.osType)"

Conteggio delle macchine virtuali per tipo di sistema operativo con estensione

Un modo diverso per scrivere la query "Count virtual machines by OS type" è extend una proprietà e assegnargli un nome temporaneo da usare all'interno della query, in questo caso os. os viene quindi usato da summarize e count() come nell'esempio a cui si fa riferimento.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| extend os = properties.storageProfile.osDisk.osType
| summarize count() by tostring(os)
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | extend os = properties.storageProfile.osDisk.osType | summarize count() by tostring(os)"

Ottenere tutti i nuovi avvisi dagli ultimi 30 giorni

Questa query fornisce un elenco di tutti gli avvisi Nuovi dell'utente, degli ultimi 30 giorni.

iotsecurityresources
| where type == 'microsoft.iotsecurity/locations/devicegroups/alerts'
| where todatetime(properties.startTimeUtc) > ago(30d) and properties.status == 'New'
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/locations/devicegroups/alerts' | where todatetime(properties.startTimeUtc) > ago(30d) and properties.status == 'New'"

Ottenere la capacità e le dimensioni di un set di scalabilità di macchine virtuali

Questa query cerca risorse di set di scalabilità di macchine virtuali e ottiene vari dettagli fra cui le dimensioni della macchina virtuale e la capacità del set di scalabilità. Questa query usa la funzione toint() per eseguire il cast della capacità in un numero, in modo che possa essere ordinato. Infine, le colonne vengono rinominate in proprietà denominate personalizzate.

Resources
| where type=~ 'microsoft.compute/virtualmachinescalesets'
| where name contains 'contoso'
| project subscriptionId, name, location, resourceGroup, Capacity = toint(sku.capacity), Tier = sku.name
| order by Capacity desc
az graph query -q "Resources | where type=~ 'microsoft.compute/virtualmachinescalesets' | where name contains 'contoso' | project subscriptionId, name, location, resourceGroup, Capacity = toint(sku.capacity), Tier = sku.name | order by Capacity desc"

Elencare tutte le estensioni installate in una macchina virtuale

Prima di tutto, questa query usa extend nel tipo di risorsa macchine virtuali per ottenere l'ID in lettere maiuscole (toupper()), il nome e il tipo del sistema operativo e le dimensioni della macchina virtuale. Ottenere l'ID risorsa in lettere maiuscole è un buon modo per prepararsi a eseguire il join a un'altra proprietà. Quindi, la query usa join con il tipo di leftouter per ottenere le estensioni della macchina virtuale associando un carattere maiuscolo substring dell'ID estensione. La parte dell'ID prima di "/extensions/<ExtensionName>" è lo stesso formato dell'ID delle macchine virtuali, quindi viene usata questa proprietà per .join Viene quindi usato summarize con make_list nel nome dell'estensione della macchina virtuale per combinare il nome di ogni estensione in cui i valori di id, OSName, OSType e VMSize sono uguali in una singola proprietà della matrice. Infine, osName minuscolo order by con asc. Per impostazione predefinita, order by è decrescente.

Resources
| where type == 'microsoft.compute/virtualmachines'
| extend
	JoinID = toupper(id),
	OSName = tostring(properties.osProfile.computerName),
	OSType = tostring(properties.storageProfile.osDisk.osType),
	VMSize = tostring(properties.hardwareProfile.vmSize)
| join kind=leftouter(
	Resources
	| where type == 'microsoft.compute/virtualmachines/extensions'
	| extend
		VMId = toupper(substring(id, 0, indexof(id, '/extensions'))),
		ExtensionName = name
) on $left.JoinID == $right.VMId
| summarize Extensions = make_list(ExtensionName) by id, OSName, OSType, VMSize
| order by tolower(OSName) asc
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | extend JoinID = toupper(id), OSName = tostring(properties.osProfile.computerName), OSType = tostring(properties.storageProfile.osDisk.osType), VMSize = tostring(properties.hardwareProfile.vmSize) | join kind=leftouter( Resources | where type == 'microsoft.compute/virtualmachines/extensions' | extend  VMId = toupper(substring(id, 0, indexof(id, '/extensions'))),  ExtensionName = name ) on \$left.JoinID == \$right.VMId | summarize Extensions = make_list(ExtensionName) by id, OSName, OSType, VMSize | order by tolower(OSName) asc"

Elencare gli aggiornamenti del sistema operativo disponibili per tutti i computer raggruppati per categoria di aggiornamento

Restituisce un elenco di sistemi operativi in sospeso per i computer.

PatchAssessmentResources
| where type !has 'softwarepatches'
| extend prop = parse_json(properties)
| extend lastTime = properties.lastModifiedDateTime
| extend updateRollupCount = prop.availablePatchCountByClassification.updateRollup, featurePackCount = prop.availablePatchCountByClassification.featurePack, servicePackCount = prop.availablePatchCountByClassification.servicePack, definitionCount = prop.availablePatchCountByClassification.definition, securityCount = prop.availablePatchCountByClassification.security, criticalCount = prop.availablePatchCountByClassification.critical, updatesCount = prop.availablePatchCountByClassification.updates, toolsCount = prop.availablePatchCountByClassification.tools, otherCount = prop.availablePatchCountByClassification.other, OS = prop.osType
| project lastTime, id, OS, updateRollupCount, featurePackCount, servicePackCount, definitionCount, securityCount, criticalCount, updatesCount, toolsCount, otherCount
az graph query -q "PatchAssessmentResources | where type !has 'softwarepatches' | extend prop = parse_json(properties) | extend lastTime = properties.lastModifiedDateTime | extend updateRollupCount = prop.availablePatchCountByClassification.updateRollup, featurePackCount = prop.availablePatchCountByClassification.featurePack, servicePackCount = prop.availablePatchCountByClassification.servicePack, definitionCount = prop.availablePatchCountByClassification.definition, securityCount = prop.availablePatchCountByClassification.security, criticalCount = prop.availablePatchCountByClassification.critical, updatesCount = prop.availablePatchCountByClassification.updates, toolsCount = prop.availablePatchCountByClassification.tools, otherCount = prop.availablePatchCountByClassification.other, OS = prop.osType | project lastTime, id, OS, updateRollupCount, featurePackCount, servicePackCount, definitionCount, securityCount, criticalCount, updatesCount, toolsCount, otherCount"

Elenco dell'installazione dell'aggiornamento del sistema operativo Linux completata

Restituisce un elenco di stato di Linux Server - Installazione dell'aggiornamento del sistema operativo eseguita per i computer negli ultimi 7 giorni.

PatchAssessmentResources
| where type has 'softwarepatches' and properties has 'version'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), version = tostring(prop.version), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications)
| where lTime > ago(7d)
| project lTime, RunID, machineName, rgName, resourceType, patchName, version, classifications, installationState
| sort by RunID
az graph query -q "PatchAssessmentResources | where type has 'softwarepatches' and properties has 'version' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), version = tostring(prop.version), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications) | where lTime > ago(7d) | project lTime, RunID, machineName, rgName, resourceType, patchName, version, classifications, installationState | sort by RunID"

Elenco delle macchine virtuali e degli stati di disponibilità associati in base agli ID risorsa

Restituisce l'elenco più recente di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate in base allo stato di disponibilità. La query fornisce anche l'ID risorsa associato in properties.targetResourceIdbase a , per semplificare il debug e la mitigazione. Gli stati di disponibilità possono essere uno dei quattro valori disponibili, non disponibili, degradati e sconosciuti. Per altri dettagli sul significato di ognuno degli stati di disponibilità, vedere Panoramica di Azure Integrità risorse.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"

Elenco di macchine virtuali per stato di disponibilità e stato di alimentazione con ID risorsa e gruppi di risorse

Restituisce un elenco di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate sullo stato di alimentazione e sullo stato di disponibilità per fornire uno stato di integrità coerente per le macchine virtuali. La query fornisce anche informazioni dettagliate sul gruppo di risorse e sull'ID risorsa associati a ogni voce per una visibilità dettagliata sulle risorse.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code)
| join kind=leftouter (
	HealthResources
	| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
	| where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines'
	| project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState))
	on $left.Id == $right.targetResourceId
| project-away targetResourceId
| where PowerState != 'PowerState/deallocated'
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code) | join kind=leftouter ( HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines' | project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on \$left.Id == \$right.targetResourceId | project-away targetResourceId | where PowerState != 'PowerState/deallocated'"

Elenco di macchine virtuali non disponibili in base agli ID risorsa

Restituisce l'elenco più recente di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate in base al relativo stato di disponibilità. L'elenco popolato evidenzia solo le macchine virtuali il cui stato di disponibilità non è "Disponibile" per assicurarsi di conoscere tutti gli stati relativi alle macchine virtuali. Quando tutte le macchine virtuali sono disponibili, è possibile aspettarsi di non ricevere risultati.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| where tostring(properties.availabilityState) != 'Available'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.availabilityState) != 'Available' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"

Elenco dell'installazione dell'aggiornamento del sistema operativo Windows Server completata

Restituisce un elenco di stato di Windows Server - Installazione degli aggiornamenti del sistema operativo eseguiti per i computer negli ultimi 7 giorni.

PatchAssessmentResources
| where type has 'softwarepatches' and properties !has 'version'
| extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10))
| extend prop = parse_json(properties)
| extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), kbId = tostring(prop.kbId), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications)
| where lTime > ago(7d)
| project lTime, RunID, machineName, rgName, resourceType, patchName, kbId, classifications, installationState
| sort by RunID
az graph query -q "PatchAssessmentResources | where type has 'softwarepatches' and properties !has 'version' | extend machineName = tostring(split(id, '/', 8)), resourceType = tostring(split(type, '/', 0)), tostring(rgName = split(id, '/', 4)), tostring(RunID = split(id, '/', 10)) | extend prop = parse_json(properties) | extend lTime = todatetime(prop.lastModifiedDateTime), patchName = tostring(prop.patchName), kbId = tostring(prop.kbId), installationState = tostring(prop.installationState), classifications = tostring(prop.classifications) | where lTime > ago(7d) | project lTime, RunID, machineName, rgName, resourceType, patchName, kbId, classifications, installationState | sort by RunID"

Visualizzare le macchine virtuali con relative interfacce di rete e IP pubblici

Questa query usa due comandi leftouterjoin per riunire le macchine virtuali create con il modello di distribuzione Resource Manager, le interfacce di rete correlate e qualsiasi indirizzo IP pubblico correlato a tali interfacce di rete.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| extend nics=array_length(properties.networkProfile.networkInterfaces)
| mv-expand nic=properties.networkProfile.networkInterfaces
| where nics == 1 or nic.properties.primary =~ 'true' or isempty(nic)
| project vmId = id, vmName = name, vmSize=tostring(properties.hardwareProfile.vmSize), nicId = tostring(nic.id)
| join kind=leftouter (
	Resources
	| where type =~ 'microsoft.network/networkinterfaces'
	| extend ipConfigsCount=array_length(properties.ipConfigurations)
	| mv-expand ipconfig=properties.ipConfigurations
	| where ipConfigsCount == 1 or ipconfig.properties.primary =~ 'true'
	| project nicId = id, publicIpId = tostring(ipconfig.properties.publicIPAddress.id))
	on nicId
| project-away nicId1
| summarize by vmId, vmName, vmSize, nicId, publicIpId
| join kind=leftouter (
	Resources
	| where type =~ 'microsoft.network/publicipaddresses'
	| project publicIpId = id, publicIpAddress = properties.ipAddress)
on publicIpId
| project-away publicIpId1
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | extend nics=array_length(properties.networkProfile.networkInterfaces) | mv-expand nic=properties.networkProfile.networkInterfaces | where nics == 1 or nic.properties.primary =~ 'true' or isempty(nic) | project vmId = id, vmName = name, vmSize=tostring(properties.hardwareProfile.vmSize), nicId = tostring(nic.id) | join kind=leftouter ( Resources | where type =~ 'microsoft.network/networkinterfaces' | extend ipConfigsCount=array_length(properties.ipConfigurations) | mv-expand ipconfig=properties.ipConfigurations | where ipConfigsCount == 1 or ipconfig.properties.primary =~ 'true' | project nicId = id, publicIpId = tostring(ipconfig.properties.publicIPAddress.id)) on nicId | project-away nicId1 | summarize by vmId, vmName, vmSize, nicId, publicIpId | join kind=leftouter ( Resources | where type =~ 'microsoft.network/publicipaddresses' | project publicIpId = id, publicIpAddress = properties.ipAddress) on publicIpId | project-away publicIpId1"

Mostrare tutte le macchine virtuali ordinate per nome in ordine decrescente

Per elencare solo le macchine virtuali (che sono di tipo Microsoft.Compute/virtualMachines), è possibile cercare le corrispondenze della proprietà type nei risultati. Analogamente alla query precedente, desc cambia order by in decrescente. Nella ricerca di corrispondenze per tipo, =~ induce Resource Graph a non distinguere fra maiuscole e minuscole.

Resources
| project name, location, type
| where type =~ 'Microsoft.Compute/virtualMachines'
| order by name desc
az graph query -q "Resources | project name, location, type | where type =~ 'Microsoft.Compute/virtualMachines' | order by name desc"

Mostrare le prime cinque macchine virtuali per nome e tipo di sistema operativo

Questa query usa top per recuperare solo cinque record corrispondenti ordinati in base al nome. Il tipo della risorsa di Azure è Microsoft.Compute/virtualMachines. project indica ad Azure Resource Graph quali proprietà includere.

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| project name, properties.storageProfile.osDisk.osType
| top 5 by name desc
az graph query -q "Resources | where type =~ 'Microsoft.Compute/virtualMachines' | project name, properties.storageProfile.osDisk.osType | top 5 by name desc"

Riepilogare la macchina virtuale in base alla proprietà estesa stati di alimentazione

Questa query usa le proprietà estese nelle macchine virtuali per riepilogare in base agli stati di alimentazione.

Resources
| where type == 'microsoft.compute/virtualmachines'
| summarize count() by tostring(properties.extended.instanceView.powerState.code)
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | summarize count() by tostring(properties.extended.instanceView.powerState.code)"

Macchine virtuali individuate da un'espressione regolare

Questa query cerca le macchine virtuali che corrispondono a un'espressione regolare (nota come regex). matches regex @ permette di definire l'espressione regolare usata per cercare le corrispondenze, ovvero ^Contoso(.*)[0-9]+$. Tale definizione di espressione regolare è spiegata come:

  • ^ - La corrispondenza deve cominciare all'inizio della stringa.
  • Contoso - Stringa con distinzione tra maiuscole e minuscole.
  • (.*) - Corrispondenza di sottoespressione:
    • . - Trova la corrispondenza di qualsiasi carattere, ad eccezione del carattere nuova riga.
    • * - Trova la corrispondenza dell'elemento precedente zero o più volte.
  • [0-9] - Corrispondenza del gruppo di caratteri per i numeri da 0 a 9.
  • + - Trova la corrispondenza dell'elemento precedente una o più volte.
  • $ - La corrispondenza dell'elemento precedente deve essere presente alla fine della stringa.

Dopo aver cercato le corrispondenze in base al nome, la query proietta il nome e applica l'ordinamento in base al nome in modo crescente.

Resources
| where type =~ 'microsoft.compute/virtualmachines' and name matches regex @'^Contoso(.*)[0-9]+$'
| project name
| order by name asc
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' and name matches regex @'^Contoso(.*)[0-9]+\$' | project name | order by name asc"

Generali

Contare le risorse di Azure

Questa query restituisce il numero di risorse di Azure esistenti nelle sottoscrizioni a cui l'utente ha accesso. È anche una query valida da usare per verificare che nella shell preferita siano installati i componenti di Azure Resource Graph appropriati e funzionino correttamente.

Resources
| summarize count()
az graph query -q "Resources | summarize count()"

Elencare le risorse interessate durante il trasferimento di una sottoscrizione di Azure

Restituisce alcune delle risorse di Azure interessate quando si trasferisce una sottoscrizione in una directory di Azure Active Directory (Azure AD) diversa. Sarà necessario ricreare alcune delle risorse esistenti prima del trasferimento della sottoscrizione.

Resources
| where type in (
	'microsoft.managedidentity/userassignedidentities',
	'microsoft.keyvault/vaults',
	'microsoft.sql/servers/databases',
	'microsoft.datalakestore/accounts',
	'microsoft.containerservice/managedclusters')
	or identity has 'SystemAssigned'
	or (type =~ 'microsoft.storage/storageaccounts' and properties['isHnsEnabled'] == true)
| summarize count() by type
az graph query -q "Resources | where type in ( 'microsoft.managedidentity/userassignedidentities', 'microsoft.keyvault/vaults', 'microsoft.sql/servers/databases', 'microsoft.datalakestore/accounts', 'microsoft.containerservice/managedclusters') or identity has 'SystemAssigned' or (type =~ 'microsoft.storage/storageaccounts' and properties['isHnsEnabled'] == true) | summarize count() by type"

Elencare le risorse ordinate per nome

Questa query restituisce qualsiasi tipo di risorsa, ma solo le proprietà name, type e location. Usa order by per ordinare le proprietà in base alla proprietà name in ordine crescente (asc).

Resources
| project name, type, location
| order by name asc
az graph query -q "Resources | project name, type, location | order by name asc"

Rimuovere colonne dai risultati

La query seguente usa summarize per contare le risorse in base a sottoscrizione, join per aggiungere i dettagli della sottoscrizione della tabella ResourceContainers, quindi project-away per rimuovere alcune colonne.

Resources
| summarize resourceCount=count() by subscriptionId
| join (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId
| project-away subscriptionId, subscriptionId1
az graph query -q "Resources | summarize resourceCount=count() by subscriptionId | join (ResourceContainers | where type=='microsoft.resources/subscriptions' | project SubName=name, subscriptionId) on subscriptionId | project-away subscriptionId, subscriptionId1"

Mostrare i tipi di risorse e le versioni dell'API

Resource Graph usa principalmente la versione non di anteprima più recente dell'API di un provider di risorse per ottenere mediante l'operazione GET le proprietà delle risorse durante un aggiornamento. In alcuni casi, la versione dell'API usata è stata sottoposta a override per fornire le proprietà più recenti o più usate nei risultati. La query seguente illustra in dettaglio la versione dell'API usata per la raccolta delle proprietà per ogni tipo di risorsa:

Resources
| distinct type, apiVersion
| where isnotnull(apiVersion)
| order by type asc
az graph query -q "Resources | distinct type, apiVersion | where isnotnull(apiVersion) | order by type asc"

IoT Defender

Conteggia tutti i sensori per tipo

Questa query riepiloga tutti i sensori in base al tipo (OT, EIoT).

iotsecurityresources
| where type == 'microsoft.iotsecurity/sensors'
| summarize count() by tostring(properties.sensorType)
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/sensors' | summarize count() by tostring(properties.sensorType)"

Contare il numero di dispositivi IoT presenti nella rete, in base al sistema operativo

Questa query riepiloga tutti i dispositivi IoT in base alla piattaforma del sistema operativo.

iotsecurityresources
| where type == 'microsoft.iotsecurity/locations/devicegroups/devices'
| summarize count() by tostring(properties.operatingSystem.platform)
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/locations/devicegroups/devices' | summarize count() by tostring(properties.operatingSystem.platform)"

Ottenere tutte le raccomandazioni di gravità elevata

Questa query fornisce un elenco di tutte le raccomandazioni relative alla gravità elevata dell'utente.

iotsecurityresources
| where type == 'microsoft.iotsecurity/locations/devicegroups/recommendations'
| where properties.severity == 'High'
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/locations/devicegroups/recommendations' | where properties.severity == 'High'"

Elencare i siti con un valore di tag specifico

Questa query fornisce un elenco di tutti i siti con un valore di tag specifico.

iotsecurityresources
| where type == 'microsoft.iotsecurity/sites'
| where properties.tags['key'] =~ 'value1'
az graph query -q "iotsecurityresources | where type == 'microsoft.iotsecurity/sites' | where properties.tags['key'] =~ 'value1'"

Gruppi di gestione

Numero di sottoscrizioni per gruppo di gestione

Riepiloga il numero di sottoscrizioni in ogni gruppo di gestione.

ResourceContainers
| where type =~ 'microsoft.management/managementgroups'
| project mgname = name
| join kind=leftouter (resourcecontainers | where type=~ 'microsoft.resources/subscriptions'
| extend  mgParent = properties.managementGroupAncestorsChain | project id, mgname = tostring(mgParent[0].name)) on mgname
| summarize count() by mgname
az graph query -q "ResourceContainers | where type =~ 'microsoft.management/managementgroups' | project mgname = name | join kind=leftouter (resourcecontainers | where type=~ 'microsoft.resources/subscriptions' | extend mgParent = properties.managementGroupAncestorsChain | project id, mgname = tostring(mgParent[0].name)) on mgname | summarize count() by mgname"

Elencare tutti i predecessori del gruppo di gestione per un gruppo di gestione specificato

Fornisce i dettagli della gerarchia dei gruppi di gestione per il gruppo di gestione specificato nell'ambito della query. In questo esempio il gruppo di gestione è denominato Application.

ResourceContainers
| where type =~ 'microsoft.management/managementgroups'
| extend  mgParent = properties.details.managementGroupAncestorsChain
| mv-expand with_itemindex=MGHierarchy mgParent
| project name, properties.displayName, mgParent, MGHierarchy, mgParent.name
az graph query -q "ResourceContainers | where type =~ 'microsoft.management/managementgroups' | extend mgParent = properties.details.managementGroupAncestorsChain | mv-expand with_itemindex=MGHierarchy mgParent | project name, properties.displayName, mgParent, MGHierarchy, mgParent.name" --management-groups Application

Elencare tutti i predecessori del gruppo di gestione per una sottoscrizione specificata

Fornisce i dettagli della gerarchia del gruppo di gestione per la sottoscrizione specificata nell'ambito della query. In questo esempio, il GUID della sottoscrizione è 11111111-1111-1111-1111-111111111111.

ResourceContainers
| where type =~ 'microsoft.resources/subscriptions'
| extend  mgParent = properties.managementGroupAncestorsChain
| mv-expand with_itemindex=MGHierarchy mgParent
| project subscriptionId, name, mgParent, MGHierarchy, mgParent.name
az graph query -q "ResourceContainers | where type =~ 'microsoft.resources/subscriptions' | extend mgParent = properties.managementGroupAncestorsChain | mv-expand with_itemindex=MGHierarchy mgParent | project subscriptionId, name, mgParent, MGHierarchy, mgParent.name" --subscriptions 11111111-1111-1111-1111-111111111111

Elencare tutte le sottoscrizioni in un gruppo di gestione specificato

Fornisce il nome e l'ID sottoscrizione di tutte le sottoscrizioni nel gruppo di gestione specificato nell'ambito della query. In questo esempio il gruppo di gestione è denominato Application.

ResourceContainers
| where type =~ 'microsoft.resources/subscriptions'
| project subscriptionId, name
az graph query -q "ResourceContainers | where type =~ 'microsoft.resources/subscriptions' | project subscriptionId, name" --management-groups Application

Punteggio di sicurezza per gruppo di gestione

Restituisce il punteggio di sicurezza per ogni gruppo di gestione.

SecurityResources
| where type == 'microsoft.security/securescores'
| project subscriptionId,
	subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)),
	weight = tolong(iff(properties.weight == 0, 1, properties.weight))
| join kind=leftouter (
	ResourceContainers
	| where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled'
	| project subscriptionId, mgChain=properties.managementGroupAncestorsChain )
	on subscriptionId
| mv-expand mg=mgChain
| summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name)
| extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2))
| project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore
| order by mgName asc
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores' | project subscriptionId, subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)), weight = tolong(iff(properties.weight == 0, 1, properties.weight)) | join kind=leftouter ( ResourceContainers | where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled' | project subscriptionId, mgChain=properties.managementGroupAncestorsChain ) on subscriptionId | mv-expand mg=mgChain | summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name) | extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2)) | project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore | order by mgName asc"

Microsoft Defender

Visualizzare tutti gli avvisi di Microsoft Defender per il cloud attivi

Restituisce un elenco di tutti gli avvisi attivi nel tenant Microsoft Defender per il cloud.

securityresources
| where type =~ 'microsoft.security/locations/alerts'
| where properties.Status in ('Active')
| where properties.Severity in ('Low', 'Medium', 'High')
| project alert_type = tostring(properties.AlertType), SystemAlertId = tostring(properties.SystemAlertId), ResourceIdentifiers = todynamic(properties.ResourceIdentifiers)
az graph query -q "securityresources | where type =~ 'microsoft.security/locations/alerts' | where properties.Status in ('Active') | where properties.Severity in ('Low', 'Medium', 'High') | project alert_type = tostring(properties AlertType), SystemAlertId = tostring(properties.SystemAlertId), ResourceIdentifiers = todynamic(properties ResourceIdentifiers)"

Controlla il punteggio di sicurezza per ogni sottoscrizione

Restituisce i controlli del punteggio di sicurezza per ogni sottoscrizione.

SecurityResources
| where type == 'microsoft.security/securescores/securescorecontrols'
| extend controlName=properties.displayName,
	controlId=properties.definition.name,
	notApplicableResourceCount=properties.notApplicableResourceCount,
	unhealthyResourceCount=properties.unhealthyResourceCount,
	healthyResourceCount=properties.healthyResourceCount,
	percentageScore=properties.score.percentage,
	currentScore=properties.score.current,
	maxScore=properties.definition.properties.maxScore,
	weight=properties.weight,
	controlType=properties.definition.properties.source.sourceType,
	controlRecommendationIds=properties.definition.properties.assessmentDefinitions
| project tenantId, subscriptionId, controlName, controlId, unhealthyResourceCount, healthyResourceCount, notApplicableResourceCount, percentageScore, currentScore, maxScore, weight, controlType, controlRecommendationIds
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores/securescorecontrols' | extend controlName=properties.displayName, controlId=properties.definition.name, notApplicableResourceCount=properties.notApplicableResourceCount, unhealthyResourceCount=properties.unhealthyResourceCount, healthyResourceCount=properties.healthyResourceCount, percentageScore=properties.score.percentage, currentScore=properties.score.current, maxScore=properties.definition.properties.maxScore, weight=properties.weight, controlType=properties.definition.properties.source.sourceType, controlRecommendationIds=properties.definition.properties.assessmentDefinitions | project tenantId, subscriptionId, controlName, controlId, unhealthyResourceCount, healthyResourceCount, notApplicableResourceCount, percentageScore, currentScore, maxScore, weight, controlType, controlRecommendationIds"

Contare le risorse integre, non integre e non applicabili per ogni raccomandazione

Restituisce il numero di risorse integre, non integre e non applicabili per ogni raccomandazione. Usare summarize e count per definire come raggruppare e aggregare i valori in base alla proprietà .

SecurityResources
| where type == 'microsoft.security/assessments'
| extend resourceId=id,
	recommendationId=name,
	resourceType=type,
	recommendationName=properties.displayName,
	source=properties.resourceDetails.Source,
	recommendationState=properties.status.code,
	description=properties.metadata.description,
	assessmentType=properties.metadata.assessmentType,
	remediationDescription=properties.metadata.remediationDescription,
	policyDefinitionId=properties.metadata.policyDefinitionId,
	implementationEffort=properties.metadata.implementationEffort,
	recommendationSeverity=properties.metadata.severity,
	category=properties.metadata.categories,
	userImpact=properties.metadata.userImpact,
	threats=properties.metadata.threats,
	portalLink=properties.links.azurePortal
| summarize numberOfResources=count(resourceId) by tostring(recommendationName), tostring(recommendationState)
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | extend resourceId=id, recommendationId=name, resourceType=type, recommendationName=properties.displayName, source=properties.resourceDetails.Source, recommendationState=properties.status.code, description=properties.metadata.description, assessmentType=properties.metadata.assessmentType, remediationDescription=properties.metadata.remediationDescription, policyDefinitionId=properties.metadata.policyDefinitionId, implementationEffort=properties.metadata.implementationEffort, recommendationSeverity=properties.metadata.severity, category=properties.metadata.categories, userImpact=properties.metadata.userImpact, threats=properties.metadata.threats, portalLink=properties.links.azurePortal | summarize numberOfResources=count(resourceId) by tostring(recommendationName), tostring(recommendationState)"

Ottenere tutti gli avvisi IoT nell'hub, filtrati per tipo

Restituisce tutti gli avvisi IoT per un hub specifico (sostituire il segnaposto {hub_id}) e il tipo di avviso (sostituire il segnaposto {alert_type}).

SecurityResources
| where type =~ 'microsoft.security/iotalerts' and id contains '{hub_id}' and properties.alertType contains '{alert_type}'
az graph query -q "SecurityResources | where type =~ 'microsoft.security/iotalerts' and id contains '{hub_id}' and properties.alertType contains '{alert_type}'"

Ottenere informazioni dettagliate sulla riservatezza di una risorsa specifica

Restituisce informazioni dettagliate sulla riservatezza di una risorsa specifica (sostituire il segnaposto {resource_id}).

SecurityResources
| where type == 'microsoft.security/insights/classification'
| where properties.associatedResource contains '$resource_id'
| project SensitivityInsight = properties.insightProperties.purviewCatalogs[0].sensitivity
az graph query -q "SecurityResources | where type == 'microsoft.security/insights/classification' | where properties.associatedResource contains '\$resource_id' | project SensitivityInsight = properties.insightProperties.purviewCatalogs[0].sensitivity"

Ottenere un avviso IoT specifico

Restituisce un avviso IoT specifico da un ID avviso di sistema fornito (sostituire il segnaposto {system_Alert_Id}).

SecurityResources
| where type =~ 'microsoft.security/iotalerts' and properties.systemAlertId contains '{system_Alert_Id}'
az graph query -q "SecurityResources | where type =~ 'microsoft.security/iotalerts' and properties.systemAlertId contains '{system_Alert_Id}'"

Elencare i risultati della valutazione della vulnerabilità del Registro Container

Restituisce tutte le vulnerabilità rilevate nelle immagini del contenitore. Microsoft Defender per contenitori deve essere abilitato per visualizzare questi risultati di sicurezza.

SecurityResources
| where type == 'microsoft.security/assessments'
| where properties.displayName contains 'Container registry images should have vulnerability findings resolved'
| summarize by assessmentKey=name //the ID of the assessment
| join kind=inner (
	securityresources
	| where type == 'microsoft.security/assessments/subassessments'
	| extend assessmentKey = extract('.*assessments/(.+?)/.*',1,  id)
) on assessmentKey
| project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId
| extend description = properties.description,
	displayName = properties.displayName,
	resourceId = properties.resourceDetails.id,
	resourceSource = properties.resourceDetails.source,
	category = properties.category,
	severity = properties.status.severity,
	code = properties.status.code,
	timeGenerated = properties.timeGenerated,
	remediation = properties.remediation,
	impact = properties.impact,
	vulnId = properties.id,
	additionalData = properties.additionalData
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | where properties.displayName contains 'Container registry images should have vulnerability findings resolved' | summarize by assessmentKey=name //the ID of the assessment | join kind=inner ( securityresources | where type == 'microsoft.security/assessments/subassessments' | extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id) ) on assessmentKey | project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId | extend description = properties.description, displayName = properties.displayName, resourceId = properties.resourceDetails.id, resourceSource = properties.resourceDetails.source, category = properties.category, severity = properties.status.severity, code = properties.status.code, timeGenerated = properties.timeGenerated, remediation = properties.remediation, impact = properties.impact, vulnId = properties.id, additionalData = properties.additionalData"

Elencare le raccomandazioni di Microsoft Defender

Restituisce tutte le valutazioni di Microsoft Defender, organizzate in modo tabulare con campo per proprietà.

SecurityResources
| where type == 'microsoft.security/assessments'
| extend resourceId=id,
	recommendationId=name,
	recommendationName=properties.displayName,
	source=properties.resourceDetails.Source,
	recommendationState=properties.status.code,
	description=properties.metadata.description,
	assessmentType=properties.metadata.assessmentType,
	remediationDescription=properties.metadata.remediationDescription,
	policyDefinitionId=properties.metadata.policyDefinitionId,
	implementationEffort=properties.metadata.implementationEffort,
	recommendationSeverity=properties.metadata.severity,
	category=properties.metadata.categories,
	userImpact=properties.metadata.userImpact,
	threats=properties.metadata.threats,
	portalLink=properties.links.azurePortal
| project tenantId, subscriptionId, resourceId, recommendationName, recommendationId, recommendationState, recommendationSeverity, description, remediationDescription, assessmentType, policyDefinitionId, implementationEffort, userImpact, category, threats, source, portalLink
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | extend resourceId=id, recommendationId=name, recommendationName=properties.displayName, source=properties.resourceDetails.Source, recommendationState=properties.status.code, description=properties.metadata.description, assessmentType=properties.metadata.assessmentType, remediationDescription=properties.metadata.remediationDescription, policyDefinitionId=properties.metadata.policyDefinitionId, implementationEffort=properties.metadata.implementationEffort, recommendationSeverity=properties.metadata.severity, category=properties.metadata.categories, userImpact=properties.metadata.userImpact, threats=properties.metadata.threats, portalLink=properties.links.azurePortal | project tenantId, subscriptionId, resourceId, recommendationName, recommendationId, recommendationState, recommendationSeverity, description, remediationDescription, assessmentType, policyDefinitionId, implementationEffort, userImpact, category, threats, source, portalLink"

Elencare i risultati della valutazione della vulnerabilità qualys

Restituisce tutte le vulnerabilità rilevate nelle macchine virtuali in cui è installato un agente Qualys.

SecurityResources
| where type == 'microsoft.security/assessments'
| where * contains 'vulnerabilities in your virtual machines'
| summarize by assessmentKey=name //the ID of the assessment
| join kind=inner (
	securityresources
	| where type == 'microsoft.security/assessments/subassessments'
	| extend assessmentKey = extract('.*assessments/(.+?)/.*',1,  id)
) on assessmentKey
| project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId
| extend description = properties.description,
	displayName = properties.displayName,
	resourceId = properties.resourceDetails.id,
	resourceSource = properties.resourceDetails.source,
	category = properties.category,
	severity = properties.status.severity,
	code = properties.status.code,
	timeGenerated = properties.timeGenerated,
	remediation = properties.remediation,
	impact = properties.impact,
	vulnId = properties.id,
	additionalData = properties.additionalData
az graph query -q "SecurityResources | where type == 'microsoft.security/assessments' | where * contains 'vulnerabilities in your virtual machines' | summarize by assessmentKey=name //the ID of the assessment | join kind=inner ( securityresources | where type == 'microsoft.security/assessments/subassessments' | extend assessmentKey = extract('.*assessments/(.+?)/.*',1, id) ) on assessmentKey | project assessmentKey, subassessmentKey=name, id, parse_json(properties), resourceGroup, subscriptionId, tenantId | extend description = properties.description, displayName = properties.displayName, resourceId = properties.resourceDetails.id, resourceSource = properties.resourceDetails.source, category = properties.category, severity = properties.status.severity, code = properties.status.code, timeGenerated = properties.timeGenerated, remediation = properties.remediation, impact = properties.impact, vulnId = properties.id, additionalData = properties.additionalData"

Stato di valutazione della conformità alle normative

Restituisce lo stato di valutazione della conformità alle normative in base allo standard e al controllo di conformità.

SecurityResources
| where type == 'microsoft.security/regulatorycompliancestandards/regulatorycompliancecontrols/regulatorycomplianceassessments'
| extend assessmentName=properties.description,
	complianceStandard=extract(@'/regulatoryComplianceStandards/(.+)/regulatoryComplianceControls',1,id),
	complianceControl=extract(@'/regulatoryComplianceControls/(.+)/regulatoryComplianceAssessments',1,id),
	skippedResources=properties.skippedResources,
	passedResources=properties.passedResources,
	failedResources=properties.failedResources,
	state=properties.state
| project tenantId, subscriptionId, id, complianceStandard, complianceControl, assessmentName, state, skippedResources, passedResources, failedResources
az graph query -q "SecurityResources | where type == 'microsoft.security/regulatorycompliancestandards/regulatorycompliancecontrols/regulatorycomplianceassessments' | extend assessmentName=properties.description, complianceStandard=extract(@'/regulatoryComplianceStandards/(.+)/regulatoryComplianceControls',1,id), complianceControl=extract(@'/regulatoryComplianceControls/(.+)/regulatoryComplianceAssessments',1,id), skippedResources=properties.skippedResources, passedResources=properties.passedResources, failedResources=properties.failedResources, state=properties.state | project tenantId, subscriptionId, id, complianceStandard, complianceControl, assessmentName, state, skippedResources, passedResources, failedResources"

Stato di conformità alle normative per standard di conformità

Restituisce lo stato di conformità alle normative in base allo standard di conformità per ogni sottoscrizione.

SecurityResources
| where type == 'microsoft.security/regulatorycompliancestandards'
| extend complianceStandard=name,
	state=properties.state,
	passedControls=properties.passedControls,
	failedControls=properties.failedControls,
	skippedControls=properties.skippedControls,
	unsupportedControls=properties.unsupportedControls
| project tenantId, subscriptionId, complianceStandard, state, passedControls, failedControls, skippedControls, unsupportedControls
az graph query -q "SecurityResources | where type == 'microsoft.security/regulatorycompliancestandards' | extend complianceStandard=name, state=properties.state, passedControls=properties.passedControls, failedControls=properties.failedControls, skippedControls=properties.skippedControls, unsupportedControls=properties.unsupportedControls | project tenantId, subscriptionId, complianceStandard, state, passedControls, failedControls, skippedControls, unsupportedControls"

Punteggio di sicurezza per gruppo di gestione

Restituisce il punteggio di sicurezza per ogni gruppo di gestione.

SecurityResources
| where type == 'microsoft.security/securescores'
| project subscriptionId,
	subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)),
	weight = tolong(iff(properties.weight == 0, 1, properties.weight))
| join kind=leftouter (
	ResourceContainers
	| where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled'
	| project subscriptionId, mgChain=properties.managementGroupAncestorsChain )
	on subscriptionId
| mv-expand mg=mgChain
| summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name)
| extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2))
| project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore
| order by mgName asc
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores' | project subscriptionId, subscriptionTotal = iff(properties.score.max == 0, 0.00, round(tolong(properties.weight) * todouble(properties.score.current)/tolong(properties.score.max),2)), weight = tolong(iff(properties.weight == 0, 1, properties.weight)) | join kind=leftouter ( ResourceContainers | where type == 'microsoft.resources/subscriptions' and properties.state == 'Enabled' | project subscriptionId, mgChain=properties.managementGroupAncestorsChain ) on subscriptionId | mv-expand mg=mgChain | summarize sumSubs = sum(subscriptionTotal), sumWeight = sum(weight), resultsNum = count() by tostring(mg.displayName), mgId = tostring(mg.name) | extend secureScore = iff(tolong(resultsNum) == 0, 404.00, round(sumSubs/sumWeight*100,2)) | project mgName=mg_displayName, mgId, sumSubs, sumWeight, resultsNum, secureScore | order by mgName asc"

Punteggio di sicurezza per sottoscrizione

Restituisce il punteggio di sicurezza per ogni sottoscrizione.

SecurityResources
| where type == 'microsoft.security/securescores'
| extend percentageScore=properties.score.percentage,
	currentScore=properties.score.current,
	maxScore=properties.score.max,
	weight=properties.weight
| project tenantId, subscriptionId, percentageScore, currentScore, maxScore, weight
az graph query -q "SecurityResources | where type == 'microsoft.security/securescores' | extend percentageScore=properties.score.percentage, currentScore=properties.score.current, maxScore=properties.score.max, weight=properties.weight | project tenantId, subscriptionId, percentageScore, currentScore, maxScore, weight"

Visualizzare Defender per il cloud piano tariffario per sottoscrizione

Restituisce Defender per il cloud piano tariffario piano tariffario per sottoscrizione.

SecurityResources
| where type == 'microsoft.security/pricings'
| project Subscription= subscriptionId, Azure_Defender_plan= name, Status= properties.pricingTier
az graph query -q "SecurityResources | where type == 'microsoft.security/pricings' | project Subscription= subscriptionId, Azure_Defender_plan= name, Status= properties.pricingTier"

Rete

Contare le risorse che hanno indirizzi IP configurati per sottoscrizione

Usando la query di esempio "Elenca tutti gli indirizzi IP pubblici" e aggiungendo summarize e count(), è possibile ottenere un elenco per sottoscrizione di risorse con indirizzi IP configurati.

Resources
| where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress)
| summarize count () by subscriptionId
az graph query -q "Resources | where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress) | summarize count () by subscriptionId"

Ottenere reti virtuali e subnet delle interfacce di rete

Usare un'espressione parse regolare per ottenere i nomi della rete virtuale e della subnet dalla proprietà ID risorsa. Anche se parse consente di ottenere dati da un campo complesso, è ottimale accedere direttamente alle proprietà se esistenti anziché usare parse.

Resources
| where type =~ 'microsoft.network/networkinterfaces'
| project id, ipConfigurations = properties.ipConfigurations
| mvexpand ipConfigurations
| project id, subnetId = tostring(ipConfigurations.properties.subnet.id)
| parse kind=regex subnetId with '/virtualNetworks/' virtualNetwork '/subnets/' subnet
| project id, virtualNetwork, subnet
az graph query -q "Resources | where type =~ 'microsoft.network/networkinterfaces' | project id, ipConfigurations = properties.ipConfigurations | mvexpand ipConfigurations | project id, subnetId = tostring(ipConfigurations.properties.subnet.id) | parse kind=regex subnetId with '/virtualNetworks/' virtualNetwork '/subnets/' subnet | project id, virtualNetwork, subnet"

Elencare tutti gli indirizzi IP pubblici

Analogamente alla query "Mostra risorse che contengono risorse di archiviazione", trovare tutto ciò che è un tipo con la parola publicIPAddresses. Questa query si espande su tale modello per includere solo i risultati in cui properties.ipAddressisnotempty, per restituire solo properties.ipAddress e ai limit risultati dai primi 100. Potrebbe essere necessario eseguire l'escape delle virgolette a seconda della shell in uso.

Resources
| where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress)
| project properties.ipAddress
| limit 100
az graph query -q "Resources | where type contains 'publicIPAddresses' and isnotempty(properties.ipAddress) | project properties.ipAddress | limit 100"

Mostrare i gruppi di sicurezza di rete non associati

Questa query restituisce gruppi di sicurezza di rete (NSG) non associati a un'interfaccia di rete o a una subnet.

Resources
| where type =~ 'microsoft.network/networksecuritygroups' and isnull(properties.networkInterfaces) and isnull(properties.subnets)
| project name, resourceGroup
| sort by name asc
az graph query -q "Resources | where type =~ 'microsoft.network/networksecuritygroups' and isnull(properties.networkInterfaces) and isnull(properties.subnets) | project name, resourceGroup | sort by name asc"

Visualizzare le macchine virtuali con indirizzi IP pubblici SKU Basic

Questa query restituisce un elenco di ID macchina virtuale con indirizzi IP pubblici SKU Basic collegati.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project vmId = tolower(id), vmNics = properties.networkProfile.networkInterfaces
| join (
  Resources |
  where type =~ 'microsoft.network/networkinterfaces' |
  project nicVMId = tolower(tostring(properties.virtualMachine.id)), allVMNicID = tolower(id), nicIPConfigs = properties.ipConfigurations)
  on $left.vmId == $right.nicVMId
| join (
  Resources
  | where type =~ 'microsoft.network/publicipaddresses' and isnotnull(properties.ipConfiguration.id)
  | where sku.name == 'Basic' // exclude to find all VMs with Public IPs
  | project pipId = id, pipSku = sku.name, pipAssociatedNicId = tolower(tostring(split(properties.ipConfiguration.id, '/ipConfigurations/')[0])))
  on $left.allVMNicID == $right.pipAssociatedNicId
| project vmId, pipId, pipSku
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | project vmId = tolower(id), vmNics = properties.networkProfile.networkInterfaces | join (Resources | where type =~ 'microsoft.network/networkinterfaces' | project nicVMId = tolower(tostring(properties.virtualMachine.id)), allVMNicID = tolower(id), nicIPConfigs = properties.ipConfigurations) on \$left.vmId == \$right.nicVMId | join ( Resources | where type =~ 'microsoft.network/publicipaddresses' and isnotnull(properties.ipConfiguration.id) | where sku.name == 'Basic' | project pipId = id, pipSku = sku.name, pipAssociatedNicId = tolower(tostring(split(properties.ipConfiguration.id, '/ipConfigurations/')[0]))) on \$left.allVMNicID == \$right.pipAssociatedNicId | project vmId, pipId, pipSku"

Resource Health

Numero di macchine virtuali per stato di disponibilità e ID sottoscrizione

Restituisce il numero di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate in base al relativo stato di disponibilità in ogni sottoscrizione.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize count() by subscriptionId, AvailabilityState = tostring(properties.availabilityState)"

Elenco delle macchine virtuali e degli stati di disponibilità associati in base agli ID risorsa

Restituisce l'elenco più recente di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate in base allo stato di disponibilità. La query fornisce anche l'ID risorsa associato in properties.targetResourceIdbase a , per semplificare il debug e la mitigazione. Gli stati di disponibilità possono essere uno dei quattro valori disponibili, non disponibili, degradati e sconosciuti. Per altri dettagli sul significato di ognuno degli stati di disponibilità, vedere Panoramica di Azure Integrità risorse.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"

Elenco di macchine virtuali per stato di disponibilità e stato di alimentazione con ID risorsa e gruppi di risorse

Restituisce un elenco di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate sullo stato di alimentazione e sullo stato di disponibilità per fornire uno stato di integrità coerente per le macchine virtuali. La query fornisce anche informazioni dettagliate sul gruppo di risorse e sull'ID risorsa associati a ogni voce per una visibilità dettagliata sulle risorse.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code)
| join kind=leftouter (
	HealthResources
	| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
	| where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines'
	| project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState))
	on $left.Id == $right.targetResourceId
| project-away targetResourceId
| where PowerState != 'PowerState/deallocated'
az graph query -q "Resources | where type =~ 'microsoft.compute/virtualmachines' | project resourceGroup, Id = tolower(id), PowerState = tostring( properties.extended.instanceView.powerState.code) | join kind=leftouter ( HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.targetResourceType) =~ 'microsoft.compute/virtualmachines' | project targetResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on \$left.Id == \$right.targetResourceId | project-away targetResourceId | where PowerState != 'PowerState/deallocated'"

Elenco di macchine virtuali non disponibili in base agli ID risorsa

Restituisce l'elenco più recente di macchine virtuali (tipo Microsoft.Compute/virtualMachines) aggregate in base al relativo stato di disponibilità. L'elenco popolato evidenzia solo le macchine virtuali il cui stato di disponibilità non è "Disponibile" per assicurarsi di conoscere tutti gli stati relativi alle macchine virtuali. Quando tutte le macchine virtuali sono disponibili, è possibile aspettarsi di non ricevere risultati.

HealthResources
| where type =~ 'microsoft.resourcehealth/availabilitystatuses'
| where tostring(properties.availabilityState) != 'Available'
| summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | where tostring(properties.availabilityState) != 'Available' | summarize by ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)"

Tag

Trovare gli account di archiviazione con un tag specifico senza distinzione tra maiuscole e minuscole nel gruppo di risorse

Analogamente alla query "Trovare account di archiviazione con un tag con distinzione tra maiuscole e minuscole nella query del gruppo di risorse", ma quando è necessario cercare un nome di tag senza distinzione tra maiuscole e minuscole e un valore di tag, usare mv-expand con il parametro bagexpansion . Questa query usa una quota maggiore rispetto alla query originale, quindi usare mv-expand solo se necessario.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
	ResourceContainers
	| where type =~ 'microsoft.resources/subscriptions/resourcegroups'
	| mv-expand bagexpansion=array tags
	| where isnotempty(tags)
	| where tags[0] =~ 'key1' and tags[1] =~ 'value1'
	| project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | mv-expand bagexpansion=array tags | where isnotempty(tags) | where tags[0] =~ 'key1' and tags[1] =~ 'value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

Trovare gli account di archiviazione con un tag specifico con distinzione tra maiuscole e minuscole nel gruppo di risorse

La query seguente usa un elemento internojoin per connettere gli account di archiviazione ai gruppi di risorse con un nome di tag e un valore di tag con distinzione tra maiuscole e minuscole specificato.

Resources
| where type =~ 'microsoft.storage/storageaccounts'
| join kind=inner (
	ResourceContainers
	| where type =~ 'microsoft.resources/subscriptions/resourcegroups'
	| where tags['Key1'] =~ 'Value1'
	| project subscriptionId, resourceGroup)
on subscriptionId, resourceGroup
| project-away subscriptionId1, resourceGroup1
az graph query -q "Resources | where type =~ 'microsoft.storage/storageaccounts' | join kind=inner ( ResourceContainers | where type =~ 'microsoft.resources/subscriptions/resourcegroups' | where tags['Key1'] =~ 'Value1' | project subscriptionId, resourceGroup) on subscriptionId, resourceGroup | project-away subscriptionId1, resourceGroup1"

Elencare tutti i nomi di tag

Questa query inizia con il tag e compila un oggetto JSON che elenca tutti i nomi di tag univoci e i tipi corrispondenti.

Resources
| project tags
| summarize buildschema(tags)
az graph query -q "Resources | project tags | summarize buildschema(tags)"

Elencare tutti i tag e i relativi valori

Questa query elenca i tag nei gruppi di gestione, nelle sottoscrizioni e nelle risorse insieme ai relativi valori. La query limita innanzitutto le risorse in cui tag isnotempty(), limita i campi inclusi includendo solo i tag in projecte e mvexpandextend per ottenere i dati associati dal contenitore delle proprietà. Usa quindi union per combinare i risultati di ResourceContainers agli stessi risultati di Resources, offrendo una copertura generale ai tag recuperati. Infine, limita i risultati ai distinct dati associati ed esclude i tag nascosti dal sistema.

ResourceContainers
| where isnotempty(tags)
| project tags
| mvexpand tags
| extend tagKey = tostring(bag_keys(tags)[0])
| extend tagValue = tostring(tags[tagKey])
| union (
	resources
	| where isnotempty(tags)
	| project tags
	| mvexpand tags
	| extend tagKey = tostring(bag_keys(tags)[0])
	| extend tagValue = tostring(tags[tagKey])
)
| distinct tagKey, tagValue
| where tagKey !startswith "hidden-"
az graph query -q "ResourceContainers | where isnotempty(tags) | project tags | mvexpand tags | extend tagKey = tostring(bag_keys(tags)[0]) | extend tagValue = tostring(tags[tagKey]) | union ( resources | where isnotempty(tags) | project tags | mvexpand tags | extend tagKey = tostring(bag_keys(tags)[0]) | extend tagValue = tostring(tags[tagKey]) ) | distinct tagKey, tagValue | where tagKey !startswith "hidden-""

Elencare le risorse con un valore di tag specifico

È possibile limitare i risultati mediante proprietà diverse dal tipo di risorsa di Azure, ad esempio un tag. In questo esempio si applica alle risorse di Azure un filtro basato sul nome di tag Environment con il valore Internal. Per fornire anche i tag della risorsa e i relativi valori, aggiungere la proprietà tags per alla parola chiave project.

Resources
| where tags.environment=~'internal'
| project name, tags
az graph query -q "Resources | where tags.environment=~'internal' | project name, tags"

Set di scalabilità di macchine virtuali

Orchestrazione uniforme del set di scalabilità di macchine virtuali

Ottenere le macchine virtuali nella modalità di orchestrazione uniform del set di scalabilità di macchine virtuali categorizzata in base allo stato di alimentazione. Questa tabella contiene la visualizzazione modello e powerState le proprietà di visualizzazione dell'istanza per le macchine virtuali che fanno parte della modalità uniforme del set di scalabilità di macchine virtuali.

È possibile eseguire query sulla visualizzazione del modello e powerState nelle proprietà di visualizzazione dell'istanza per le macchine virtuali che fanno parte della modalità flessibile del set di scalabilità di macchine virtuali tramite Resources la tabella.

ComputeResources
| where type =~ 'microsoft.compute/virtualmachinescalesets/virtualmachines'
| extend powerState = properties.extended.instanceView.powerState.code
| project name, powerState, id
az graph query -q "ComputeResources | where type =~ 'microsoft.compute/virtualmachinescalesets/virtualmachines' | extend powerState = properties.extended.instanceView.powerState.code | project name, powerState, id"

Orchestrazione flessibile del set di scalabilità di macchine virtuali

Ottenere macchine virtuali in modalità di orchestrazione flessibile del set di scalabilità di macchine virtuali classificate in base allo stato di alimentazione. Questa tabella contiene la visualizzazione del modello e powerState le proprietà della visualizzazione dell'istanza per le macchine virtuali che fanno parte della modalità flessibile del set di scalabilità di macchine virtuali.

Resources
| where type == 'microsoft.compute/virtualmachines'
| extend powerState = tostring(properties.extended.instanceView.powerState.code)
| extend VMSS = tostring(properties.virtualMachineScaleSet.id)
| where isnotempty(VMSS)
| project name, powerState, id
az graph query -q "Resources | where type == 'microsoft.compute/virtualmachines' | extend powerState = tostring(properties.extended.instanceView.powerState.code) | extend VMSS = tostring(properties.virtualMachineScaleSet.id) | where isnotempty(VMSS) | project name, powerState, id"

Passaggi successivi