Share via


Query di esempio di Azure Resource Graph per Azure Macchine virtuali

Questa pagina è una raccolta di query di esempio di Azure Resource Graph per Azure Macchine virtuali. Per un elenco completo degli esempi di Azure Resource Graph, vedere Esempi di Resource Graph per categoria ed Esempi di Resource Graph per tabella.

Query di esempio

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"

Passaggi successivi