如何使用Invoke-AzCostManagementQuery分组结果?遇空值表达式错误
解决Invoke-AzCostManagementQuery分组时的空值表达式错误
问题原因
你遇到的空值表达式错误,核心原因是分组参数格式不符合cmdlet要求:-DatasetGrouping参数需要接收数组类型的分组配置,而非单个哈希表;另外旧版本Az.CostManagement模块可能存在参数解析bug。
解决方案
1. 修正分组参数格式
即使只有一个分组规则,也必须用@()将哈希表包裹为数组:
$grouping = @( @{ name = "azcosts" type = "TagKey" } )
2. 升级Az.CostManagement模块到最新版本
旧版本模块可能存在参数解析bug,执行以下命令升级:
Update-Module -Name Az.CostManagement -Force
3. 完整可执行命令示例
# 设置范围 $scope = "/subscriptions/xxxxxx" # 定义成本聚合 $aggregation = @{ totalCost = @{ name = "Cost" function = "SUM" } } # 定义分组(数组格式) $grouping = @( @{ name = "azcosts" type = "TagKey" } ) # 执行查询 Invoke-AzCostManagementQuery ` -Scope $scope ` -Timeframe 'DateToMonth' ` -Type 'Usage' ` -DatasetGranularity "Daily" ` -DatasetAggregation $aggregation ` -DatasetGrouping $grouping
额外排查点
- 确认标签
azcosts在当前订阅的资源上实际存在,否则会返回空结果(但不会触发空值错误) - 如果仍有问题,添加
-Debug参数查看详细请求日志,定位具体错误点:Invoke-AzCostManagementQuery ` -Scope $scope ` -Timeframe 'DateToMonth' ` -Type 'Usage' ` -DatasetGranularity "Daily" ` -DatasetAggregation $aggregation ` -DatasetGrouping $grouping ` -Debug
内容的提问来源于stack exchange,提问作者Gill-Bates
相关产品推荐
相关产品推荐

