HereToLearn
HereToLearn

Reputation: 11

Count number of VMs based on Management Group names

I would like to create a Graph QL query or a Powershell script(preferred) that would display the Total number of VMs in all Azure subscriptions along with number of VMs in management groups containing a certain string and count of rest of the VMs under management groups which doesn't have that specific string

Resources
| where type =~ 'Microsoft.Compute/virtualMachines'
| Count
| project TotalVMs=Count

Upvotes: 0

Views: 249

Answers (1)

Venkat V
Venkat V

Reputation: 7669

Total number of VMs in all Azure subscriptions along with number of VMs in management groups containing a certain string and count of rest of the VMs under management groups which doesn't have that specific string.

I have followed this MS Doc1 & MSDoc2 as a reference.

Here is the Powershell script to display the total number of VMs in all Azure subscriptions along with number of VMs inmanagement groups containing a certain string.

> Connect-AzAccount 
> Select-AzSubscription -All 
> $searchString = "vm"
> $mgmtGroups = Get-AzManagementGroup
> $totalVMs = 0 
> $matchingVMs = 0 
> $nonMatchingVMs = 0
> foreach ($mgmtGroup in $mgmtGroups) {
> Write-Host "Checking management group $($mgmtGroup.DisplayName)"
>     $vms = Get-AzResource -ResourceType "Microsoft.Compute/virtualMachines"
>     $vms.Name
>     $vmCount = $vms.Count
>     $totalVMs += $vmCount
>     if ($vmCount -gt 0) {
>         $matchingVMCount = ($vms | Where-Object { $_.Name -like "*$searchString*" }).Count
>         $matchingVMs += $matchingVMCount
>         $nonMatchingVMs += ($vmCount - $matchingVMCount)
>     }
>  Write-Host "Found $vmCount VMs in the management group"
>  Write-Host "Found $matchingVMCount VMs containing '$searchString'" }

> Write-Host "Total VMs in all subscriptions: $totalVMs" Write-Host
> "Matching VMs in Management Group: $matchingVMs" Write-Host
> "Non-matching VMs in Management Group: $nonMatchingVMs"

Output:

enter image description here

Upvotes: 0

Related Questions