如何使用PowerShell获取Azure订阅的多维度成本数据?
Azure订阅成本查询PowerShell脚本方案
前置操作
- 安装成本管理模块:
Install-Module -Name Az.CostManagement -Force -AllowClobber
- 登录并切换到目标订阅:
Connect-AzAccount Set-AzContext -SubscriptionId "你的订阅ID" # 或自动获取当前订阅ID:Set-AzContext -SubscriptionId (Get-AzContext).Subscription.Id
1. 过去6个月按服务维度的成本数据
# 定义时间范围 $startDate = (Get-Date).AddMonths(-6).ToString("yyyy-MM-dd") $endDate = (Get-Date).ToString("yyyy-MM-dd") # 查询按服务分组的成本 Get-AzCostManagementQuery -Scope "/subscriptions/你的订阅ID" ` -TimePeriodStart $startDate -TimePeriodEnd $endDate ` -Type ActualCost ` -Grouping @{Type="Dimension"; Name="ServiceName"} ` -Aggregation @{TotalCost = @{Name="PreTaxCost"; Function="Sum"}} # 导出到CSV:追加 | Export-Csv -Path "服务维度成本.csv" -NoTypeInformation
2. 过去6个月按资源组及资源维度的成本数据
$startDate = (Get-Date).AddMonths(-6).ToString("yyyy-MM-dd") $endDate = (Get-Date).ToString("yyyy-MM-dd") # 查询按资源组+资源分组的成本 Get-AzCostManagementQuery -Scope "/subscriptions/你的订阅ID" ` -TimePeriodStart $startDate -TimePeriodEnd $endDate ` -Type ActualCost ` -Grouping @(@{Type="Dimension"; Name="ResourceGroupName"}, @{Type="Dimension"; Name="ResourceName"}) ` -Aggregation @{TotalCost = @{Name="PreTaxCost"; Function="Sum"}} # 导出到CSV:追加 | Export-Csv -Path "资源组-资源维度成本.csv" -NoTypeInformation
3. 过去15天的每日成本数据
$startDate = (Get-Date).AddDays(-15).ToString("yyyy-MM-dd") $endDate = (Get-Date).ToString("yyyy-MM-dd") # 查询每日成本 Get-AzCostManagementQuery -Scope "/subscriptions/你的订阅ID" ` -TimePeriodStart $startDate -TimePeriodEnd $endDate ` -Type ActualCost ` -Grouping @{Type="Dimension"; Name="Date"} ` -Aggregation @{TotalCost = @{Name="PreTaxCost"; Function="Sum"}} ` -Timeframe Custom # 导出到CSV:追加 | Export-Csv -Path "近15天每日成本.csv" -NoTypeInformation
注意事项
- 替换所有
你的订阅ID为实际订阅ID,或使用自动获取命令避免手动输入 - 若需查询包含预留实例、节省计划的摊销成本,可将
-Type ActualCost改为-Type AmortizedCost - 大跨度时间查询可能耗时较长,可适当缩小时间范围或添加
-Wait参数确保查询完成
内容的提问来源于stack exchange,提问作者Vidhan Bhaskar
相关产品推荐
相关产品推荐

