多个订阅时按资源组统计虚拟机

Count VMs by resource groups when multiple subscriptions

我创建了一个 PowerShell 脚本,该脚本将导出到一个 Excel 文件,详细介绍在 Azure 中产生成本的组件。

在一个名为“详细信息”的选项卡中,导出了在特定计费周期内产生成本的所有组件。 在另一个名为“Short”的选项卡中,导出了所有产生费用的 VM 的计数(按订阅过滤)。

我尝试了多种方法,但无法满足新的要求。

如何计算按资源组筛选的所有产生成本的 VM。 如果您能提供帮助,我将不胜感激。

干杯!

If (-not(Get-InstalledModule ImportExcel -ErrorAction silentlycontinue)) {
    Write-Output "Module does not exist"
  }
  Else {
    Write-Output "Module ImportExcel exists. Continuing with gathering data."
  }
  
$file=".\resources.xlsx"

# Because Get-AzBilling gives us the value as yyyyMM we need also a value for day.
# Used $billingperiodfinal to generate the correct value to be used.
$billingperiod = (Get-AzBillingPeriod)[1].Name
$day = "01"
$billingperiodfinal = $billingperiod+$day
$date=Get-Date -format "yyy-MM-dd"
$time2=(Get-Date).addmonths(-1)
$date2=Get-Date $time2 -format "yyy-MM"

$VMs = @()
$Subscriptions = Get-AzSubscription
foreach ($sub in $Subscriptions) {
  Get-AzSubscription -SubscriptionName $sub.Name | Set-AzContext
  az account set -s $sub.Name
  $VMs += (az consumption usage list -p $billingperiodfinal | ConvertFrom-Json)
}

$VMsDetails = $VMs

$VMsDetails | Export-Excel -path $file -ClearSheet -workSheetName "Detailed"

$VMsShort = $VMs `
| Where-Object {($_.product -Match "Virtual Machines")} `
| Sort-Object -Property instanceName -Descending `
| Select-Object instanceName, subscriptionName `
| Get-Unique -AsString `
| Group-Object subscriptionName | Select-Object Name,Count `
| Select-Object @{ expression={$_.Name}; label='Subscription Name' }, @{ expression={$_.Count}; label='Number of VMs' }

$VMsShort | Export-Excel -path $file -ClearSheet -workSheetName "Short"

我将 az consumption usage list 换成了 Get-AzConsumptionUsageDetail,因为我可以在他们的帮助页面上看到输出,而且我知道它会将 ResourceGroup 作为参数。这个遍历您的组并将组名添加为 属性 的建议应该可以通过任何一种方式工作:

$Subscriptions = Get-AzSubscription

# Iterate through subs
$AzConsumption = foreach ($sub in $Subscriptions) {
  Set-AzContext $sub
  $AzResourceGroups = Get-AzResourceGroup | sort ResourceGroupName

  # Iterate through each resource group
  Foreach ($rg in $AzResourceGroups) {  

    # Get the consumption usage - this can be replaced with the 'az consumption usage list' command
    $RgConsumption = Get-AzConsumptionUsageDetail -ResourceGroup $rg.ResourceGroupName -BillingPeriodName (Get-AzBillingPeriod)[1].Name 
    # Add ResourceGroup as a property to consumption report.
    $RgConsumption | Add-Member -MemberType NoteProperty -Name ResourceGroup -Value $rg.ResourceGroupName
    $RgConsumption
  }
}

$AzConsumptionShort = $AzConsumption |
  Where Product -Match "Virtual Machines" |
  Sort InstanceName -Descending | 
  Select InstanceName,SubscriptionName,ResourceGroup -Unique |
  Group subscriptionName |
  Select @{l='Subscription Name';e={$_.Name}},@{l='Number of VMs';e={$_.Count}}

# etc.