多个订阅时按资源组计算 VM

时间:2021-04-05 15:46:20

标签: azure powershell azure-powershell

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

在名为“详细信息”的选项卡中,导出了在特定计费周期内产生成本的所有组件。 在另一个名为“Short”的选项卡中,导出了按订阅过滤的所有生成成本的 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"

1 个答案:

答案 0 :(得分:0)

我将 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.