Przykładowe zapytania usługi Azure Resource Graph według tabeli

Ta strona jest kolekcją przykładowych zapytań usługi Azure Resource Graph pogrupowanych według tabeli. Aby przejść do określonej tabeli, użyj linków w górnej części strony. W przeciwnym razie użyj klawiszy Ctrl-F, aby użyć funkcji wyszukiwania przeglądarki. Aby uzyskać listę tabel i powiązanych szczegółów, zobacz Tabele usługi Resource Graph.

AdvisorResources

Podsumowanie oszczędności kosztów z usługi Azure Advisor

To zapytanie podsumowuje oszczędności kosztów każdego zalecenia usługi 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"

Wyświetlanie listy serwerów z obsługą usługi Arc, na których nie jest uruchomiona najnowsza wersja agenta wydanego

To zapytanie zwraca wszystkie serwery z obsługą usługi Arc z nieaktualną wersją agenta Połączenie maszyny. Agenci ze stanem Wygasły są wykluczeni z wyników. Zapytanie używa funkcji leftouterjoin, aby zebrać rekomendacje doradcy zgłoszone dotyczące wszystkich agentów maszyny Połączenie zidentyfikowanych jako nieaktualne, a maszyny komputerów hybrydowych do filtrowania dowolnego agenta, który nie komunikował się z platformą Azure w danym okresie.

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"

AppServiceResources

Wyświetlanie listy wersji protokołu TLS usługi aplikacja systemu Azure

Wyświetl minimalną wersję protokołu TLS (Transport Layer Security) usługi aplikacja systemu Azure Service dla żądań przychodzących do aplikacji internetowej.

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"

AuthorizationResources

Rozwiązywanie problemów z limitami kontroli dostępu opartej na rolach platformy Azure

Tabela authorizationresources może służyć do rozwiązywania problemów z kontrolą dostępu opartą na rolach (RBAC) platformy Azure w przypadku przekroczenia limitów. Aby uzyskać więcej informacji, zobacz Rozwiązywanie problemów z limitami kontroli dostępu opartej na rolach platformy Azure.

Pobieranie przypisań ról z właściwościami klucza

Udostępnia przykład przypisań ról i niektóre odpowiednie właściwości zasobów.

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"

Pobieranie definicji ról z kluczowymi właściwościami

Udostępnia przykład definicji ról i niektóre odpowiednie właściwości zasobów.

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"

Pobieranie definicji ról za pomocą akcji

Przedstawia przykład definicji ról z rozszerzoną listą akcji, a nie akcjami dla listy uprawnień każdej definicji roli.

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"

Pobieranie definicji ról z wyświetlonymi uprawnieniami

Przedstawia podsumowanie wartości Actions i notActions dla każdej unikatowej definicji roli.

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"

Uzyskiwanie administratorów klasycznych z kluczowymi właściwościami

Udostępnia przykład klasycznych administratorów i niektóre odpowiednie właściwości zasobów.

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"

ComputeResources

Jednolita aranżacja zestawu skalowania maszyn wirtualnych

Uzyskaj maszyny wirtualne w trybie ujednoliconej aranżacji zestawu skalowania maszyn wirtualnych według ich stanu zasilania. Ta tabela zawiera widok modelu i powerState właściwości widoku wystąpienia dla części maszyn wirtualnych w trybie jednolitym zestawu skalowania maszyn wirtualnych.

Widok modelu i powerState właściwości widoku wystąpienia dla części maszyn wirtualnych w trybie elastycznym zestawu skalowania maszyn wirtualnych można wykonywać zapytania za pośrednictwem Resources tabeli.

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"

ExtendedLocationResources

Uzyskiwanie typów zasobów z włączoną obsługą usługi Azure Arc w lokalizacjach niestandardowych

Zawiera listę włączonych typów zasobów dla niestandardowych lokalizacji z obsługą usługi Azure Arc.

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

Wyświetlanie listy lokalizacji niestandardowych z obsługą usługi Azure Arc z włączonym programem VMware lub programem SCVMM

Zawiera listę wszystkich niestandardowych lokalizacji z włączoną obsługą usługi Azure Arc, które mają włączone typy zasobów VMware lub SCVMM.

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"

GuestConfigurationResources

Liczba maszyn w zakresie zasad konfiguracji gościa

Przedstawia liczbę maszyn wirtualnych platformy Azure i serwerów połączonych z usługą Arc w zakresie przypisań konfiguracji gościa usługi Azure Policy.

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"

Liczba niezgodnych przypisań konfiguracji gościa

Przedstawia liczbę niezgodnych maszyn na przyczynę przypisania konfiguracji gościa. Ogranicza wyniki do pierwszych 100 w celu uzyskania wydajności.

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"

Znajdź wszystkie przyczyny, dla których maszyna nie jest zgodna z przypisaniami konfiguracji gościa

Wyświetl wszystkie przyczyny przypisania konfiguracji gościa dla określonej maszyny. Usuń pierwszą where klauzulę, aby uwzględnić również inspekcje, gdzie maszyna jest zgodna.

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"

Wyświetlanie listy maszyn i stanu oczekującego ponownego uruchomienia

Zawiera listę maszyn ze szczegółami konfiguracji dotyczącymi tego, czy mają oczekujący ponowny rozruch.

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"

Wyświetlanie listy maszyn, które nie są uruchomione, oraz ostatni stan zgodności

Zawiera listę maszyn, które nie są włączone z przypisaniami konfiguracji i ostatnim zgłoszonym stanem zgodności.

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"

Szczegóły zapytania dotyczące raportów przypisań konfiguracji gościa

Wyświetl raport ze szczegółów przyczyny przypisania konfiguracji gościa. W poniższym przykładzie zapytanie zwraca tylko wyniki, w których znajduje installed_application_linux się nazwa przypisania gościa, a dane wyjściowe zawierają ciąg Chrome umożliwiający wyświetlenie listy wszystkich maszyn z systemem Linux, na których zainstalowano pakiet zawierający nazwę 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"

HealthResources

Liczba maszyn wirtualnych według stanu dostępności i identyfikatora subskrypcji

Zwraca liczbę maszyn wirtualnych (typ Microsoft.Compute/virtualMachines) zagregowanych według ich stanu dostępności w każdej subskrypcji.

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)"

Lista maszyn wirtualnych i skojarzonych stanów dostępności według identyfikatorów zasobów

Zwraca najnowszą listę maszyn wirtualnych (typ Microsoft.Compute/virtualMachines) zagregowanych według stanu dostępności. Zapytanie udostępnia również skojarzony identyfikator zasobu na properties.targetResourceIdpodstawie elementu w celu łatwego debugowania i ograniczania ryzyka. Stany dostępności mogą być jedną z czterech wartości: Dostępne, Niedostępne, Obniżone i Nieznane. Aby uzyskać więcej informacji na temat znaczenia poszczególnych stanów dostępności, zobacz Omówienie usługi Azure Resource Health.

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)"

Lista maszyn wirtualnych według stanu dostępności i stanu zasilania z identyfikatorami zasobów i grupami zasobów

Zwraca listę maszyn wirtualnych (typ Microsoft.Compute/virtualMachines) zagregowanych na ich stanie zasilania i stanu dostępności, aby zapewnić spójny stan kondycji maszyn wirtualnych. Zapytanie zawiera również szczegółowe informacje dotyczące grupy zasobów i identyfikatora zasobu skojarzonego z każdym wpisem w celu uzyskania szczegółowego wglądu w zasoby.

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'"

Lista maszyn wirtualnych, które nie są dostępne według identyfikatorów zasobów

Zwraca najnowszą listę maszyn wirtualnych (typ Microsoft.Compute/virtualMachines) zagregowanych według ich stanu dostępności. Wypełniona lista wyróżnia tylko maszyny wirtualne, których stan dostępności nie jest "Dostępny", aby upewnić się, że znasz wszystkie stany, w których znajdują się maszyny wirtualne. Gdy wszystkie maszyny wirtualne są dostępne, możesz oczekiwać, że nie otrzymasz żadnych wyników.

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)"

Lista zasobów ze stanami dostępności, których dotyczyły nieplanowane zdarzenia kondycji inicjowane przez platformę

Zwraca najnowszą listę maszyn wirtualnych, których dotyczy nieplanowane zakłócenia, które zostały nieoczekiwanie wyzwolone przez platformę Azure. To zapytanie zwraca wszystkie maszyny wirtualne, których dotyczy problem, agregowane przez ich właściwość ID, wraz z odpowiednim stanem dostępności i skojarzona adnotacja (properties.reason) podsumowującą określone zakłócenia.

HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| where  properties.category == 'Unplanned' and  properties.context != 'Customer Initiated'
| project ResourceId = tolower(tostring(properties.targetResourceId)), Annotation = tostring(properties.reason)
| join (
    HealthResources
    | where type == 'microsoft.resourcehealth/availabilitystatuses'
    | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on ResourceId
| project ResourceId, AvailabilityState, Annotation
az graph query -q "HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | where  properties.category == 'Unplanned' and  properties.context != 'Customer Initiated' | project ResourceId = tolower(tostring(properties.targetResourceId)), Annotation = tostring(properties.reason) | join (HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)) on ResourceId | project ResourceId, AvailabilityState, Annotation"

Lista niedostępnych zasobów z odpowiednimi szczegółami adnotacji

Zwraca listę maszyn wirtualnych, które nie są obecnie w stanie Dostępne , agregowane według ich właściwości ID. Zapytanie pokazuje również rzeczywisty stan dostępności maszyn wirtualnych, a także powiązane ze nimi szczegóły, w tym przyczynę niedostępności.

HealthResources
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| where  properties.availabilityState != 'Available'
| project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState)
| join ( 
    HealthResources
    | where type == "microsoft.resourcehealth/resourceannotations"
    | project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category)) on ResourceId
| project ResourceId, AvailabilityState, Reason, Context, Category
az graph query -q "HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | where  properties.availabilityState != 'Available' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState) | join (HealthResources | where type == "microsoft.resourcehealth/resourceannotations" |  project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category)) on ResourceId | project ResourceId, AvailabilityState, Reason, Context, Category"

Liczba zasobów w regionie, które zostały dotknięte zakłóceniami dostępności wraz z typem wpływu

Zwraca liczbę maszyn wirtualnych, które nie są obecnie w stanie Dostępne , agregowane przez ich właściwość ID. Zapytanie pokazuje również odpowiednią lokalizację i szczegóły adnotacji, w tym przyczynę, że maszyny wirtualne nie są w stanie Dostępny .

HealthResources
| where type == 'microsoft.resourcehealth/availabilitystatuses'
| where  properties.availabilityState != 'Available'
| project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location
| join ( 
    HealthResources
    | where type == "microsoft.resourcehealth/resourceannotations"
    | project ResourceId = tolower(tostring(properties.targetResourceId)), Context = tostring(properties.context), Category = tostring(properties.category), Location = location) on ResourceId
| summarize NumResources = count(ResourceId) by Location, Context, Category
az graph query -q "HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | where  properties.availabilityState != 'Available' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location | join (HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | project ResourceId = tolower(tostring(properties.targetResourceId)), Context = tostring(properties.context), Category = tostring(properties.category), Location = location) on ResourceId | summarize NumResources = count(ResourceId) by Location, Context, Category"

Lista zasobów, na które ma wpływ określone zdarzenie kondycji, wraz z czasem wpływu, szczegółami wpływu, stanem dostępności i regionem

Zwraca listę maszyn wirtualnych, których dotyczy adnotacja VirtualMachineHostRebootedForRepair , zagregowana przez ich właściwość ID. Zapytanie zwraca również odpowiedni stan dostępności maszyn wirtualnych, czas zakłóceń i szczegóły adnotacji, w tym przyczynę wpływu.

HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| where properties.AnnotationName contains 'VirtualMachineHostRebootedForRepair'
| project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category), Location = location, Timestamp = tostring(properties.occurredTime)
| join ( 
     HealthResources
    | where type == 'microsoft.resourcehealth/availabilitystatuses'
    | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId
| project ResourceId, Reason, Context, Category, AvailabilityState, Timestamp
az graph query -q "HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | where properties.AnnotationName contains 'VirtualMachineHostRebootedForRepair' | project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Context = tostring(properties.context), Category = tostring(properties.category), Location = location, Timestamp = tostring(properties.occuredTime) | join (HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId | project ResourceId, Reason, Context, Category, AvailabilityState, Timestamp"

Lista zasobów, na które mają wpływ zdarzenia planowane na region

Zwraca listę maszyn wirtualnych, których dotyczy planowana konserwacja lub operacje naprawy przeprowadzane przez platformę Azure, zagregowane według ich właściwości ID. Zapytanie zwraca również odpowiedni stan dostępności maszyn wirtualnych, czas zakłóceń, lokalizację i szczegóły adnotacji, w tym przyczynę wpływu.

HealthResources
| where type == "microsoft.resourcehealth/resourceannotations"
| where properties.category contains 'Planned'
| project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Location = location, Timestamp = tostring(properties.occuredTime)
| join ( 
     HealthResources
    | where type == 'microsoft.resourcehealth/availabilitystatuses'
    | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId
| project ResourceId, Reason, AvailabilityState, Timestamp, Location
az graph query -q "HealthResources | where type == "microsoft.resourcehealth/resourceannotations" | where properties.category contains 'Planned' | project ResourceId = tolower(tostring(properties.targetResourceId)), Reason = tostring(properties.reason), Location = location, Timestamp = tostring(properties.occuredTime) | join (HealthResources | where type == 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(tostring(properties.targetResourceId)), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId | project ResourceId, Reason, AvailabilityState, Timestamp, Location"

Lista zasobów, których dotyczyły nieplanowane zakłócenia platformy, wraz z dostępnością, stanami zasilania i lokalizacją

Zwraca listę maszyn wirtualnych, których dotyczy planowana konserwacja lub operacje naprawy przeprowadzane przez platformę Azure, zagregowane według ich właściwości ID. Zapytanie pokazuje również odpowiedni stan dostępności maszyn wirtualnych, stan zasilania i szczegóły lokalizacji.

HealthResources
| where type =~ 'microsoft.resourcehealth/resourceannotations'
| where tostring(properties.context) == 'Platform Initiated' and tostring(properties.category) == 'Planned'
| project ResourceId = tolower(properties.targetResourceId), Location = location
| join (
    HealthResources
    | where type =~ 'microsoft.resourcehealth/availabilitystatuses'
    | project ResourceId = tolower(properties.targetResourceId), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId
| join (
    Resources
    | where type =~ 'microsoft.compute/virtualmachines'
    | project ResourceId = tolower(id), PowerState = properties.extended.instanceView.powerState.code, Location = location) on ResourceId
| project ResourceId, AvailabilityState, PowerState, Location
az graph query -q "HealthResources | where type =~ 'microsoft.resourcehealth/resourceannotations' | where tostring(properties.context) == 'Platform Initiated' and tostring(properties.category) == 'Planned' | project ResourceId = tolower(properties.targetResourceId), Location = location | join (HealthResources | where type =~ 'microsoft.resourcehealth/availabilitystatuses' | project ResourceId = tolower(properties.targetResourceId), AvailabilityState = tostring(properties.availabilityState), Location = location) on ResourceId | join (Resources | where type =~ 'microsoft.compute/virtualmachines' | project ResourceId = tolower(id), PowerState = properties.extended.instanceView.powerState.code, Location = location) on ResourceId | project ResourceId, AvailabilityState, PowerState, Location"

Bieżąca kondycja maszyn wirtualnych w wystąpieniu wirtualnym dla oprogramowania SAP

To zapytanie pobiera bieżącą kondycję dostępności wszystkich maszyn wirtualnych systemu SAP, biorąc pod uwagę identyfikator SID wystąpienia wirtualnego dla oprogramowania SAP. Zastąp mySubscriptionId ciąg identyfikatorem subskrypcji i zastąp myResourceId ciąg identyfikatorem zasobu wystąpienia wirtualnego dla oprogramowania 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"

Obecnie w złej kondycji maszyny wirtualne i adnotacje w wystąpieniu wirtualnym dla oprogramowania SAP

To zapytanie pobiera listę maszyn wirtualnych systemu SAP, które są w złej kondycji i odpowiednie adnotacje, biorąc pod uwagę identyfikator SID wystąpienia wirtualnego dla oprogramowania SAP. Zastąp mySubscriptionId ciąg identyfikatorem subskrypcji i zastąp myResourceId ciąg identyfikatorem zasobu wystąpienia wirtualnego dla oprogramowania 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"

HealthResourceChanges

Maszyny wirtualne platformy Azure, których dotyczy konserwacja zainicjowana przez platformę Azure

Zwraca listę maszyn wirtualnych, których dotyczy rutynowe operacje konserwacji zainicjowane przez platformę Azure w ciągu ostatnich 14 dni, wraz z odpowiednim powodem wpływu.

HealthResourceChanges
| where properties.targetResourceType =~ 'microsoft.resourcehealth/resourceannotations'
| where properties['changes']['properties.category']['newValue'] =~ 'Planned'
| project Id = tostring(split(tolower(properties.targetResourceId), '/providers/microsoft.resourcehealth/resourceannotations')[0]), Reason = properties['changes']['properties.reason']['newValue']
az graph query -q "HealthResourceChanges | where properties.targetResourceType =~ 'microsoft.resourcehealth/resourceannotations' | where properties['changes']['properties.category']['newValue'] =~ 'Planned' | project Id = tostring(split(tolower(properties.targetResourceId), '/providers/microsoft.resourcehealth/resourceannotations')[0]), Reason = properties['changes']['properties.reason']['newValue']"

Zmiany adnotacji dotyczących kondycji w ciągu ostatnich 14 dni

Zwraca listę wszystkich zmian adnotacji dotyczących kondycji w ciągu ostatnich 14 dni. Wartości null wskazują, że nie było aktualizacji tego konkretnego pola, co odpowiada zmianie pola Annotation Name )

healthresourcechanges
| where type == "microsoft.resources/changes"
| where properties.targetResourceType =~ "microsoft.resourcehealth/resourceannotations"
| extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/resourceAnnotations/current')[0]),
Timestamp = todatetime(properties.changeAttributes.timestamp), AnnotationName = properties['changes']['properties.annotationName']['newValue'], Reason = properties['changes']['properties.reason']['newValue'],
Context = properties['changes']['properties.context']['newValue'], Category = properties['changes']['properties.category']['newValue']
| where isnotempty(AnnotationName)
| project Timestamp, Id, PreviousAnnotation = properties['changes']['properties.annotationName']['previousValue'], AnnotationName, Reason, Context, Category
| order by Timestamp desc
az graph query -q "healthresourcechanges | where type == "microsoft.resources/changes" | where properties.targetResourceType =~ "microsoft.resourcehealth/resourceannotations" | extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/resourceAnnotations/current')[0]), Timestamp = todatetime(properties.changeAttributes.timestamp), AnnotationName = properties['changes']['properties.annotationName']['newValue'], Reason = properties['changes']['properties.reason']['newValue'], Context = properties['changes']['properties.context']['newValue'], Category = properties['changes']['properties.category']['newValue'] | where isnotempty(AnnotationName) | project Timestamp, Id, PreviousAnnotation = properties['changes']['properties.annotationName']['previousValue'], AnnotationName, Reason, Context, Category | order by Timestamp desc"

Zmiany stanu dostępności maszyny wirtualnej w ciągu ostatnich 14 dni

Zwraca listę wszystkich zmian w stanach dostępności maszyn wirtualnych w ciągu ostatnich 14 dni.

healthresourcechanges
| where type == "microsoft.resources/changes"
| where properties.targetResourceType =~ "microsoft.resourcehealth/availabilityStatuses"
| extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/availabilityStatuses/current')[0]),
Timestamp = todatetime(properties.changeAttributes.timestamp), PreviousAvailabilityState = properties['changes']['properties.availabilityState']['previousValue'],
LatestAvailabilityState = properties['changes']['properties.availabilityState']['newValue']
| where isnotempty(LatestAvailabilityState)
| project Timestamp, Id, PreviousAvailabilityState, LatestAvailabilityState
| order by Timestamp desc
az graph query -q "healthresourcechanges | where type == "microsoft.resources/changes" | where properties.targetResourceType =~ "microsoft.resourcehealth/availabilityStatuses" | extend Id = tolower(split(properties.targetResourceId, '/providers/Microsoft.ResourceHealth/availabilityStatuses/current')[0]), Timestamp = todatetime(properties.changeAttributes.timestamp), PreviousAvailabilityState = properties['changes']['properties.availabilityState']['previousValue'], LatestAvailabilityState = properties['changes']['properties.availabilityState']['newValue'] | where isnotempty(LatestAvailabilityState) | project Timestamp, Id, PreviousAvailabilityState, LatestAvailabilityState | order by Timestamp desc"

Zmiany kondycji maszyn wirtualnych i adnotacji w wystąpieniu wirtualnym dla oprogramowania SAP

To zapytanie pobiera historyczne zmiany w kondycji dostępności i odpowiadające adnotacje wszystkich maszyn wirtualnych systemu SAP, biorąc pod uwagę identyfikator SID wystąpienia wirtualnego dla oprogramowania SAP. Zastąp mySubscriptionId ciąg identyfikatorem subskrypcji i zastąp myResourceId ciąg identyfikatorem zasobu wystąpienia wirtualnego dla oprogramowania 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"

InsightResources

Wyświetlanie listy maszyn wirtualnych ze skojarzeniami reguł zbierania danych

To zapytanie wyświetla listę maszyn wirtualnych ze skojarzeniami reguł zbierania danych. Dla każdej maszyny wirtualnej wyświetla skojarzone z nią reguły zbierania danych.

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"

IoT Defender

Pobieranie wszystkich nowych alertów z ostatnich 30 dni

To zapytanie zawiera listę wszystkich nowych alertów użytkownika z ostatnich 30 dni.

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'"

IotSecurityResources

Zlicz wszystkie czujniki według typu

To zapytanie podsumowuje wszystkie czujniki według ich typu (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)"

Zlicz, ile urządzeń IoT znajduje się w sieci, według systemu operacyjnego

To zapytanie podsumowuje wszystkie urządzenia IoT według platformy systemu operacyjnego.

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)"

Uzyskiwanie wszystkich zaleceń dotyczących wysokiej ważności

To zapytanie zawiera listę wszystkich zaleceń dotyczących wysokiej ważności użytkownika.

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'"

Wyświetlanie listy witryn z określoną wartością tagu

To zapytanie udostępnia listę wszystkich witryn z określoną wartością tagu.

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'"

KubernetesConfigurationResources

Wyświetlanie listy wszystkich klastrów Kubernetes z włączoną usługą Azure Arc za pomocą rozszerzenia usługi Azure Monitor

Zwraca identyfikator połączonego klastra dla każdego klastra Kubernetes z włączoną usługą Azure Arc, który ma zainstalowane rozszerzenie usługi Azure Monitor.

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"

Wyświetlanie listy wszystkich klastrów Kubernetes z włączoną usługą Azure Arc bez rozszerzenia usługi Azure Monitor

Zwraca identyfikator połączonego klastra dla każdego klastra Kubernetes z włączoną usługą Azure Arc, który nie ma rozszerzenia usługi Azure Monitor.

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"

Wyświetl listę wszystkich Połączenie edClusters i ManagedClusters, które zawierają konfigurację flux

Zwraca wartości connectedCluster i managedCluster Ids dla klastrów zawierających co najmniej jedną wartość 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"

Wyświetlanie listy wszystkich konfiguracji strumienia, które są w stanie niezgodnym

Zwraca identyfikatory fluxConfiguration konfiguracji, które nie mogą synchronizować zasobów w klastrze.

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"

OrbitalResources

Wyświetlanie listy nadchodzących kontaktów

To zapytanie pomaga klientom śledzić wszystkie nadchodzące kontakty posortowane według czasu rozpoczęcia rezerwacji.

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"

Lista ostatnich "x" dni kontaktów na określonej stacji naziemnej

To zapytanie pomaga klientom śledzić wszystkie kontakty z ostatnich x dni posortowane według czasu rozpoczęcia rezerwacji dla określonej stacji naziemnej. Funkcja now(-1d) określa liczbę ostatnich dni.

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"

Wyświetlanie listy kontaktów z ostatnich "x" dni w określonym profilu kontaktowym

To zapytanie pomaga klientom śledzić wszystkie kontakty z ostatnich x dni posortowane według czasu rozpoczęcia rezerwacji dla określonego profilu kontaktu. Funkcja now(-1d) określa liczbę ostatnich dni.

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"

PatchAssessmentResources

Liczba wykonanych instalacji aktualizacji systemu operacyjnego

Zwraca listę stanu przebiegów instalacji aktualizacji systemu operacyjnego wykonanych dla maszyn w ciągu ostatnich 7 dni.

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"

Lista dostępnych aktualizacji systemu operacyjnego dla wszystkich maszyn pogrupowanych według kategorii aktualizacji

Zwraca listę oczekujących systemów operacyjnych dla maszyn.

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"

Lista wykonanych instalacji aktualizacji systemu operacyjnego Linux

Zwraca listę stanu systemu Linux Server — instalacja aktualizacji systemu operacyjnego wykonywana dla maszyn w ciągu ostatnich 7 dni.

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"

Lista wykonanych instalacji aktualizacji systemu operacyjnego Windows Server

Zwraca listę stanu systemu Windows Server — przebiegi instalacji aktualizacji systemu operacyjnego wykonane dla maszyn w ciągu ostatnich 7 dni.

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"

PolicyResources

Zgodność według przypisania zasad

Zapewnia stan zgodności, procent zgodności i liczbę zasobów dla każdego przypisania usługi Azure Policy.

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"

Zgodność według typu zasobu

Zapewnia stan zgodności, procent zgodności i liczbę zasobów dla każdego typu zasobu.

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"

Wyświetlanie listy wszystkich niezgodnych zasobów

Zawiera listę wszystkich typów zasobów, które są w NonCompliant stanie.

PolicyResources
| where type == 'microsoft.policyinsights/policystates'
| where properties.complianceState == 'NonCompliant'
az graph query -q "PolicyResources | where type == 'microsoft.policyinsights/policystates' | where properties.complianceState == 'NonCompliant'"

Podsumowanie zgodności zasobów według stanu

Szczegóły liczby zasobów w każdym stanie zgodności.

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"

Podsumowanie zgodności zasobów według stanu na lokalizację

Szczegóły liczby zasobów w każdym stanie zgodności na lokalizację.

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"

Wykluczenia z zasad na przypisanie

Wyświetla listę liczby wykluczeń dla każdego przypisania.

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

Aby uzyskać więcej informacji na temat korzystania z zakresów za pomocą interfejsu wiersza polecenia platformy Azure lub programu Azure PowerShell, zobacz Count Azure resources (Liczba zasobów platformy Azure).

Użyj parametru --management-groups z identyfikatorem grupy zarządzania platformy Azure lub identyfikatorem dzierżawy. W tym przykładzie zmienna tenantid przechowuje identyfikator dzierżawy.

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

Wykluczenia z zasad wygasające w ciągu 90 dni

Wyświetla nazwę i datę wygaśnięcia.

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"

ZasobyKontenery

Łączenie wyników z dwóch zapytań w jeden wynik

Poniższe zapytanie używa union metody do pobierania wyników z tabeli ResourceContainers i dodawania ich do wyników z tabeli Resources .

ResourceContainers
| where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type  | limit 5
| union  (Resources | project name, type | limit 5)
az graph query -q "ResourceContainers | where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type | limit 5 | union (Resources | project name, type | limit 5)"

Liczba subskrypcji na grupę zarządzania

Podsumowuje liczbę subskrypcji w każdej grupie zarządzania.

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"

Wyświetlanie listy wszystkich elementów podrzędnych grupy zarządzania dla określonej grupy zarządzania

Zawiera szczegóły hierarchii grup zarządzania dla grupy zarządzania określonej w zakresie zapytania. W tym przykładzie grupa zarządzania nosi nazwę Aplikacja.

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

Wyświetlanie listy wszystkich elementów podrzędnych grupy zarządzania dla określonej subskrypcji

Zawiera szczegóły hierarchii grup zarządzania dla subskrypcji określonej w zakresie zapytania. W tym przykładzie identyfikator GUID subskrypcji to 111111111-1111-1111-1111-1111111111111111111.

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

Wyświetlanie listy wszystkich subskrypcji w ramach określonej grupy zarządzania

Zawiera nazwę i identyfikator subskrypcji wszystkich subskrypcji w grupie zarządzania określonej w zakresie zapytania. W tym przykładzie grupa zarządzania nosi nazwę Aplikacja.

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

Wyświetlanie listy wszystkich tagów i ich wartości

To zapytanie zawiera listę tagów grup zarządzania, subskrypcji i zasobów wraz z ich wartościami. Zapytanie najpierw ogranicza zasoby, w których tagi isnotempty(), ogranicza uwzględnione pola tylko przez uwzględnienie tagów w projectobiekcie i i mvexpandextend pobranie sparowanych danych z torby właściwości. Następnie używa union metody , aby połączyć wyniki z usługi ResourceContainers z tymi samymi wynikami z zasobów, co daje szeroki zakres, do którego są pobierane tagi. Na koniec ogranicza wyniki do distinct sparowanych danych i wyklucza tagi ukryte przez system.

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-""

Usuwanie kolumn z wyników

Poniższe zapytanie używa summarize metody do zliczenia zasobów według subskrypcji, join aby połączyć je ze szczegółami subskrypcji z tabeli ResourceContainers , a następnie project-away usunąć niektóre kolumny.

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"

Wskaźnik bezpieczeństwa dla grupy zarządzania

Zwraca wskaźnik bezpieczeństwa dla grupy zarządzania.

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"

Zasoby

Łączenie wyników z dwóch zapytań w jeden wynik

Poniższe zapytanie używa union metody do pobierania wyników z tabeli ResourceContainers i dodawania ich do wyników z tabeli Resources .

ResourceContainers
| where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type  | limit 5
| union  (Resources | project name, type | limit 5)
az graph query -q "ResourceContainers | where type=='microsoft.resources/subscriptions/resourcegroups' | project name, type | limit 5 | union (Resources | project name, type | limit 5)"

Liczba zasobów platformy Azure

To zapytanie zwraca liczbę zasobów platformy Azure, które istnieją w subskrypcjach, do których masz dostęp. Jest to również dobre zapytanie do weryfikowania, czy wybrana powłoka ma zainstalowane odpowiednie składniki usługi Azure Resource Graph w kolejności pracy.

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

Liczba zasobów magazynu kluczy

To zapytanie używa count zamiast summarize do zliczenia zwracanych rekordów. Tylko magazyny kluczy są uwzględniane w liczbie.

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

Liczba maszyn wirtualnych według stanu zasilania

Zwraca liczbę maszyn wirtualnych (typ Microsoft.Compute/virtualMachines) sklasyfikowanych według ich stanu zasilania. Aby uzyskać więcej informacji na temat stanów zasilania, zobacz Omówienie stanów zasilania.

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)"

Liczba zasobów ze skonfigurowanymi adresami IP według subskrypcji

Korzystając z przykładowego zapytania "Lista wszystkich publicznych adresów IP" i dodawania summarize i count(), możemy uzyskać listę według subskrypcji zasobów ze skonfigurowanymi adresami IP.

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"

Liczba maszyn wirtualnych według typu systemu operacyjnego

Opierając się na poprzednim zapytaniu, nadal ograniczamy wyniki według zasobów platformy Azure typu Microsoft.Compute/virtualMachines, ale nie ograniczamy już liczby zwracanych rekordów. Zamiast tego użyliśmy elementów summarize i count(), aby określić sposób grupowania i agregacji wartości według właściwości, którą w tym przykładzie jest properties.storageProfile.osDisk.osType. Aby zobaczyć przykład przedstawiający wygląd tego ciągu w pełnym obiekcie, zobacz badanie zasobów — odnajdywanie maszyn wirtualnych.

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)"

Zlicz maszyny wirtualne według typu systemu operacyjnego z rozszerzeniem

Innym sposobem na zapisanie zapytania "Liczba maszyn wirtualnych według typu systemu operacyjnego" jest extend właściwość i nadanie jej tymczasowej nazwy do użycia w zapytaniu, w tym przypadku systemu operacyjnego. system operacyjny jest następnie używany przez summarize element i count() tak jak w przykładzie, do którego odwołuje się odwołanie.

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)"

Znajdowanie kont magazynu z określonym tagiem bez uwzględniania wielkości liter w grupie zasobów

Podobnie jak w zapytaniu "Znajdź konta magazynu z określonym tagiem wrażliwym na wielkość liter w grupie zasobów", ale gdy konieczne jest wyszukanie nazwy tagu bez uwzględniania wielkości liter i wartości tagu, należy użyć mv-expand z parametrem bagexpansion . To zapytanie używa większego limitu przydziału niż oryginalne zapytanie, dlatego należy użyć mv-expand tylko w razie potrzeby.

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"

Znajdowanie kont magazynu z określonym tagiem uwzględniającym wielkość liter w grupie zasobów

Poniższe zapytanie używa wewnętrznego join konta magazynu z grupami zasobów, które mają określoną nazwę tagu z uwzględnieniem wielkości liter i wartość tagu.

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"

Pobieranie liczby i wartości procentowych serwerów z obsługą usługi Arc według domeny

To zapytanie podsumowuje właściwość domainName na serwerach z obsługą usługi Azure Arc i używa obliczeń z parametrem bin , aby utworzyć kolumnę Pct dla procentu serwerów z obsługą usługi Arc na domenę.

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)"

Uzyskiwanie pojemności zestawu skalowania i rozmiaru maszyny wirtualnej

To zapytanie szuka zasobów zestawu skalowania maszyn wirtualnych i pobiera różne szczegółowe informacje, takie jak rozmiar maszyny wirtualnej i pojemność zestawu skalowania. To zapytanie używa funkcji toint(), aby rzutować pojemność na liczbę, co pozwala na sortowanie. Na koniec następuje zmiana nazw kolumn na właściwości o niestandardowej nazwie.

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"

Pobieranie sieci wirtualnych i podsieci interfejsów sieciowych

Użyj wyrażenia parse regularnego, aby uzyskać nazwy sieci wirtualnej i podsieci z właściwości identyfikatora zasobu. Chociaż parse umożliwia pobieranie danych ze złożonego pola, optymalne jest uzyskiwanie dostępu do właściwości bezpośrednio, jeśli istnieją zamiast używać polecenia 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"

Magazyny kluczy o nazwie subskrypcji

Poniższe zapytanie przedstawia złożone użycie typu join z typemleftouter. Zapytanie ogranicza tabelę przyłączoną do zasobów subskrypcji i zawiera project tylko oryginalne pole subscriptionId inazwę pola zmieniono na SubName. Zmiana nazwy pola pozwala uniknąć join dodawania go jako nazwy1 , ponieważ pole już istnieje w zasobach. Oryginalna tabela jest filtrowana za pomocą where elementu , a poniżej project znajdują się kolumny z obu tabel. Wynik zapytania to wszystkie magazyny kluczy, które wyświetlają typ, nazwę magazynu kluczy i nazwę subskrypcji, w którym się znajduje.

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"

Wyświetlanie listy wszystkich klastrów Kubernetes z włączoną usługą Azure Arc bez rozszerzenia usługi Azure Monitor

Zwraca identyfikator połączonego klastra dla każdego klastra Kubernetes z włączoną usługą Azure Arc, który nie ma rozszerzenia usługi Azure Monitor.

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"

Wyświetlanie listy wszystkich zasobów platformy Kubernetes z włączoną usługą Azure Arc

Zwraca listę każdego klastra Kubernetes z obsługą usługi Azure Arc i odpowiednie metadane dla każdego klastra.

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'"

Wyświetl listę wszystkich Połączenie edClusters i ManagedClusters, które zawierają konfigurację flux

Zwraca wartości connectedCluster i managedCluster Ids dla klastrów zawierających co najmniej jedną wartość 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"

Wyświetlanie listy wszystkich rozszerzeń zainstalowanych na maszynie wirtualnej

Najpierw to zapytanie używa extend typu zasobu maszyn wirtualnych, aby uzyskać identyfikator w wielkiej literze (toupper()) identyfikator, uzyskać nazwę i typ systemu operacyjnego oraz uzyskać rozmiar maszyny wirtualnej. Uzyskanie identyfikatora zasobu w wielkiej literze to dobry sposób przygotowania do dołączenia do innej właściwości. Następnie zapytanie używa typu z typem leftouter, aby uzyskać rozszerzenia maszyny wirtualnej, pasując do wielkich liter substring identyfikatora join rozszerzenia. Część identyfikatora przed wartością "/extensions/<ExtensionName>" jest taka sama jak identyfikator maszyn wirtualnych, dlatego używamy tej właściwości dla joinelementu . summarize Parametr jest następnie używany make_list z nazwą rozszerzenia maszyny wirtualnej, aby połączyć nazwę każdego rozszerzenia, w którym id, OSName, OSType i VMSize są takie same w jednej właściwości tablicy. Na koniec małe order by litery OSName z asc. Domyślnie order by jest malejąco.

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"

Wyświetlanie listy wszystkich rozszerzeń zainstalowanych na serwerze z obsługą usługi Azure Arc

Najpierw to zapytanie używa project typu zasobu maszyny hybrydowej, aby uzyskać identyfikator w wielkiej litery (toupper()), uzyskać nazwę komputera i system operacyjny uruchomiony na maszynie. Uzyskanie identyfikatora zasobu w wielkiej litery to dobry sposób przygotowania do join innej właściwości. Następnie zapytanie używa join typu z typem leftouter, aby uzyskać rozszerzenia, pasując do wielkich liter substring identyfikatora rozszerzenia. Część identyfikatora przed /extensions/<ExtensionName> jest tym samym formatem co identyfikator maszyny hybrydowej, dlatego używamy tej właściwości dla elementu join. summarize Parametr jest następnie używany make_list z nazwą rozszerzenia maszyny wirtualnej, aby połączyć nazwę każdego rozszerzenia, w którym id, OSName i ComputerName są takie same w jednej właściwości tablicy. Na koniec zamawiamy małymi literami OSName przy użyciu polecenia asc. Domyślnie order by jest malejąco.

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"

Wyświetlanie listy wszystkich konfiguracji strumienia, które są w stanie niezgodnym

Zwraca identyfikatory fluxConfiguration konfiguracji, które nie mogą synchronizować zasobów w klastrze.

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"

Lista wszystkich publicznych adresów IP

Podobnie jak w zapytaniu "Pokaż zasoby zawierające magazyn", znajdź wszystko, co jest typem z wyrazem publicIPAddresses. To zapytanie rozszerza ten wzorzec, aby uwzględnić tylko wyniki, w których właściwości.ipAddress, aby zwrócić tylko właściwości.ipAddressisnotempty i wyniki limit według pierwszych 100. W zależności od wybranej powłoki może być konieczne zastosowanie znaku ucieczki dla cudzysłowów.

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"

Lista wszystkich kont magazynu z konkretną wartością tagu

Połącz funkcję filtrowania z poprzedniego przykładu i przefiltruj typ zasobów platformy Azure według właściwości typ. To zapytanie ogranicza także nasze wyszukiwanie do określonych typów zasobów platformy Azure o określonej nazwie i wartości tagu.

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'"

Wyświetlanie listy wszystkich nazw tagów

To zapytanie rozpoczyna się od tagu i tworzy obiekt JSON zawierający listę wszystkich unikatowych nazw tagów i odpowiadających im typów.

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

Wyświetlanie listy wszystkich tagów i ich wartości

To zapytanie zawiera listę tagów grup zarządzania, subskrypcji i zasobów wraz z ich wartościami. Zapytanie najpierw ogranicza zasoby, w których tagi isnotempty(), ogranicza uwzględnione pola tylko przez uwzględnienie tagów w projectobiekcie i i mvexpandextend pobranie sparowanych danych z torby właściwości. Następnie używa union metody , aby połączyć wyniki z usługi ResourceContainers z tymi samymi wynikami z zasobów, co daje szeroki zakres, do którego są pobierane tagi. Na koniec ogranicza wyniki do distinct sparowanych danych i wyklucza tagi ukryte przez system.

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-""

Wyświetlanie listy serwerów z obsługą usługi Arc, na których nie jest uruchomiona najnowsza wersja agenta wydanego

To zapytanie zwraca wszystkie serwery z obsługą usługi Arc z nieaktualną wersją agenta Połączenie maszyny. Agenci ze stanem Wygasły są wykluczeni z wyników. Zapytanie używa funkcji leftouterjoin, aby zebrać rekomendacje doradcy zgłoszone dotyczące wszystkich agentów maszyny Połączenie zidentyfikowanych jako nieaktualne, a maszyny komputerów hybrydowych do filtrowania dowolnego agenta, który nie komunikował się z platformą Azure w danym okresie.

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"

Wyświetlanie listy lokalizacji niestandardowych z obsługą usługi Azure Arc z włączonym programem VMware lub programem SCVMM

Zawiera listę wszystkich niestandardowych lokalizacji z włączoną obsługą usługi Azure Arc, które mają włączone typy zasobów VMware lub SCVMM.

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"

Wyświetlanie listy usługi Azure Cosmos DB z określonymi lokalizacjami zapisu

Następujące limity zapytań do zasobów usługi Azure Cosmos DB są używane mv-expand do rozszerzania torby właściwości dla właściwości properties.writeLocations, a następnie projektują określone pola i ograniczają wyniki dalej do wartości properties.writeLocations.locationName pasujących do wartości "Wschodnie stany USA" lub "Zachodnie stany USA".

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"

Wyświetlanie listy zasobów, których dotyczy wpływ podczas przenoszenia subskrypcji platformy Azure

Zwraca niektóre zasoby platformy Azure, które mają wpływ podczas przenoszenia subskrypcji do innego katalogu usługi Azure Active Directory (Azure AD). Należy ponownie utworzyć niektóre zasoby, które istniały przed przeniesieniem subskrypcji.

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"

Wyświetlanie listy maszyn, które nie są uruchomione, oraz ostatni stan zgodności

Zawiera listę maszyn, które nie są włączone z przypisaniami konfiguracji i ostatnim zgłoszonym stanem zgodności.

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"

Lista maszyn wirtualnych według stanu dostępności i stanu zasilania z identyfikatorami zasobów i grupami zasobów

Zwraca listę maszyn wirtualnych (typ Microsoft.Compute/virtualMachines) zagregowanych na ich stanie zasilania i stanu dostępności, aby zapewnić spójny stan kondycji maszyn wirtualnych. Zapytanie zawiera również szczegółowe informacje dotyczące grupy zasobów i identyfikatora zasobu skojarzonego z każdym wpisem w celu uzyskania szczegółowego wglądu w zasoby.

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'"

Lista zasobów posortowana według nazwy

To zapytanie zwraca dowolny typ zasobu, ale tylko właściwości nazwa, typ i lokalizacja. Używa ono polecenia order by do sortowania właściwości według właściwości nazwa w kolejności rosnącej (asc).

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

Lista zasobów z konkretną wartością tagu

Możemy ograniczyć wyniki za pomocą właściwości innych niż typ zasobu platformy Azure, takich jak tag. W tym przykładzie filtrujemy zasoby platformy Azure za pomocą nazwy tagu Środowisko o wartości Wewnętrzne. Aby uzyskać także nazwy i wartości tagów w zasobie, dodaj właściwość tagi do słowa kluczowego project.

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

Wyświetlanie listy baz danych SQL i ich elastycznych pul

Poniższe zapytanie używa funkcji leftouterjoin do łączenia zasobów usługi SQL Database i powiązanych pul elastycznych, jeśli istnieją.

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"

Wyświetlanie listy maszyn wirtualnych przy użyciu interfejsu sieciowego i publicznego adresu IP

To zapytanie używa dwóch poleceń po lewej stroniejoin do łączenia maszyn wirtualnych utworzonych za pomocą modelu wdrażania usługi Resource Manager, powiązanych interfejsów sieciowych i dowolnego publicznego adresu IP powiązanego z tymi interfejsami sieciowymi.

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"

Usuwanie kolumn z wyników

Poniższe zapytanie używa summarize metody do zliczenia zasobów według subskrypcji, join aby połączyć je ze szczegółami subskrypcji z tabeli ResourceContainers , a następnie project-away usunąć niektóre kolumny.

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"

Pokaż wszystkie maszyny wirtualne uporządkowane według nazwy w kolejności malejącej

Aby wyświetlić listę zawierającą tylko maszyny wirtualne (które są typu Microsoft.Compute/virtualMachines), możemy dopasować w wynikach właściwość typ. Podobnie jak w przypadku poprzedniego zapytania, element desc zmienia order by na kolejność malejącą. =~ w dopasowaniu typu nakazuje usłudze Resource Graph ignorowanie wielkości liter.

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"

Pokaż pierwsze pięć maszyn wirtualnych według nazwy i ich typu systemu operacyjnego

To zapytanie używa top metody do pobierania tylko pięciu pasujących rekordów uporządkowanych według nazwy. Typ zasobu platformy Azure to Microsoft.Compute/virtualMachines. project informuje usługę Azure Resource Graph, które właściwości mają być uwzględnione.

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"

Pokaż typy zasobów i wersje interfejsu API

Usługa Resource Graph używa przede wszystkim najnowszej wersji zapoznawczej interfejsu API dostawcy zasobów do GET właściwości zasobów podczas aktualizacji. W niektórych przypadkach używana wersja interfejsu API została zastąpiona w celu zapewnienia bardziej aktualnych lub powszechnie używanych właściwości w wynikach. Następujące zapytanie zawiera szczegółowe informacje o wersji interfejsu API używanej do zbierania właściwości dla każdego typu zasobu:

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"

Pokaż zasoby, które zawierają magazyn

Zamiast jawnie definiować typ do dopasowania, to przykładowe zapytanie znajdzie każdy zasób platformy Azure, który zawiera (contains) słowo magazyn.

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

Pokaż niezwiązane sieciowe grupy zabezpieczeń

To zapytanie zwraca sieciowe grupy zabezpieczeń, które nie są skojarzone z interfejsem sieciowym ani podsiecią.

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"

Podsumowywanie maszyny wirtualnej według właściwości rozszerzonej stanów zasilania

To zapytanie używa właściwości rozszerzonych na maszynach wirtualnych do podsumowania według stanów zasilania.

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)"

Wyświetlanie maszyn wirtualnych dopasowanych przez wyrażenie regularne

To zapytanie szuka maszyn wirtualnych, które odpowiadają wyrażeniu regularnemu (nazywanemu regex). Polecenie matches regex @ pozwala na określenie wyrażenia regularnego do dopasowania, czyli ^Contoso(.*)[0-9]+$. Definicja tego wyrażenia regularnego jest wyjaśniona jako:

  • ^ - Dopasowanie musi zaczynać się od początku ciągu.
  • Contoso - Ciąg z uwzględnieniem wielkości liter.
  • (.*) - Dopasowanie podwyrażu:
    • . - Dopasowuje dowolny pojedynczy znak (z wyjątkiem nowego wiersza).
    • * - Dopasowuje poprzedni element zero lub więcej razy.
  • [0-9] - Dopasowanie grupy znaków dla cyfry od 0 do 9.
  • + - Dopasowuje poprzedni element co najmniej raz.
  • $ - Dopasowanie poprzedniego elementu musi wystąpić na końcu ciągu.

Po dopasowaniu według nazwy zapytanie rzutuje nazwę i porządkuje rosnąco według nazwy.

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"

Pokaż maszyny wirtualne z publicznymi adresami IP jednostki SKU w warstwie Podstawowa

To zapytanie zwraca listę identyfikatorów maszyn wirtualnych z dołączonymi publicznymi adresami IP jednostki SKU w warstwie Podstawowa.

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"

Zlicz reguły zbierania danych usługi Azure Monitor według subskrypcji i grupy zasobów

To zapytanie grupuje reguły zbierania danych usługi Azure Monitor według subskrypcji i grupy zasobów.

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"

Zlicz reguły zbierania danych usługi Azure Monitor według lokalizacji

To zapytanie grupuje reguły zbierania danych usługi Azure Monitor według lokalizacji.

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"

Wyświetlanie listy reguł zbierania danych usługi Azure Monitor z obszarem roboczym usługi Log Analytics jako miejscem docelowym

Pobierz listę obszarów roboczych usługi Log Analytics i dla każdego obszaru roboczego wyświetl reguły zbierania danych, które określają obszar roboczy jako jeden z miejsc docelowych.

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"

Wyświetlanie listy reguł zbierania danych, które używają metryk usługi Azure Monitor jako jednego z jej miejsc docelowych

To zapytanie wyświetla listę reguł zbierania danych, które używają metryk usługi Azure Monitor jako jednej z jego miejsc docelowych.

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"

Elastyczna aranżacja zestawu skalowania maszyn wirtualnych

Uzyskaj maszyny wirtualne w trybie elastycznej aranżacji zestawu skalowania maszyn wirtualnych podzielone na kategorie zgodnie ze stanem zasilania. Ta tabela zawiera widok modelu i powerState właściwości widoku wystąpienia dla części maszyn wirtualnych w trybie elastycznym zestawu skalowania maszyn wirtualnych.

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"

SecurityResources

Kontroluje wskaźnik bezpieczeństwa na subskrypcję

Zwraca wskaźnik bezpieczeństwa kontrolek na subskrypcję.

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"

Liczba zasobów w dobrej kondycji, złej kondycji i nie dotyczy na zalecenie

Zwraca liczbę zasobów w dobrej kondycji, złej kondycji i nie dotyczy na zalecenie. Użyj i summarizecount , aby zdefiniować sposób grupowania i agregowania wartości według właściwości.

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)"

Pobieranie wszystkich alertów IoT w centrum, filtrowanych według typu

Zwraca wszystkie alerty IoT dla określonego centrum (zastąp symbol zastępczy {hub_id}) i typ alertu (zastąp symbol zastępczy {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}'"

Uzyskiwanie szczegółowych informacji o poufności określonego zasobu

Zwraca szczegółowe informacje o poufności określonego zasobu (zastąp symbol zastępczy {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"

Uzyskiwanie określonego alertu IoT

Zwraca określony alert IoT według podanego identyfikatora alertu systemu (zastąp symbol zastępczy {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}'"

Wyświetlanie listy wyników oceny luk w zabezpieczeniach usługi Container Registry

Zwraca wszystkie luki w zabezpieczeniach znalezione na obrazach kontenerów. Aby wyświetlić te ustalenia zabezpieczeń, należy włączyć usługę Microsoft Defender for Containers.

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"

Wyświetlanie listy zaleceń usługi Microsoft Defender

Zwraca wszystkie oceny usługi Microsoft Defender uporządkowane w tabelaryczny sposób z polem na właściwość.

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"

Wyświetlanie listy wyników oceny luk w zabezpieczeniach qualys

Zwraca wszystkie luki w zabezpieczeniach znalezione na maszynach wirtualnych z zainstalowanym agentem 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"

Stan ocen zgodności z przepisami

Zwraca stan ocen zgodności z przepisami zgodnie ze standardem zgodności i kontrolą.

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"

Stan zgodności z przepisami zgodnie ze standardem zgodności

Zwraca stan zgodności z przepisami na standard zgodności dla subskrypcji.

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"

Wskaźnik bezpieczeństwa dla grupy zarządzania

Zwraca wskaźnik bezpieczeństwa dla grupy zarządzania.

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"

Wskaźnik bezpieczeństwa na subskrypcję

Zwraca wskaźnik bezpieczeństwa na subskrypcję.

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"

Pokaż warstwę cenową planu Defender dla Chmury na subskrypcję

Zwraca plan Defender dla Chmury plan warstwy cenowej na subskrypcję.

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"

ServiceHealthResources

Wpływ subskrypcji zdarzeń usługi Active Service Health

Zwraca wszystkie aktywne zdarzenia usługi Service Health — w tym problemy z usługą, planowaną konserwację, porady dotyczące kondycji i biuletyny zabezpieczeń — pogrupowane według typu zdarzenia i uwzględniając liczbę subskrypcji, których dotyczy problem.

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"

Wszystkie aktywne zdarzenia doradcze dotyczące kondycji

Zwraca wszystkie aktywne zdarzenia usługi Service Health w ramach wszystkich subskrypcji, do których użytkownik ma dostęp.

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()"

Wszystkie aktywne zdarzenia planowanej konserwacji

Zwraca wszystkie aktywne zdarzenia usługi Service Health planowanej konserwacji we wszystkich subskrypcjach, do których użytkownik ma dostęp.

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()"

Wszystkie aktywne zdarzenia usługi Service Health

Zwraca wszystkie aktywne zdarzenia usługi Service Health we wszystkich subskrypcjach, do których użytkownik ma dostęp, w tym problemy z usługą, planowana konserwacja, porady dotyczące kondycji i biuletyny zabezpieczeń.

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')"

Wszystkie aktywne zdarzenia problemów z usługą

Zwraca wszystkie aktywne zdarzenia usługi Service Health (awaria) we wszystkich subskrypcjach, do których użytkownik ma dostęp.

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'"

Następne kroki

  • Dowiedz się więcej o języku zapytań.
  • Dowiedz się więcej o sposobie eksplorowania zasobów.