无法通过PowerShell调用Azure预留详情API的报错问题
解决Invoke-AzRestMethod调用预留详情API时的"queryOptionName"空值错误
问题重现
调用Azure消耗API的预留详情接口时,直接在Invoke-AzRestMethod的Path参数中拼接查询参数会触发以下错误:
"Bad Request. The argument 'queryOptionName' is null or empty"
原执行命令:
Invoke-AzRestMethod -Method GET -Path "/providers/Microsoft.Capacity/reservationorders/$reservationOrderId/reservations/$ReservationId/providers/Microsoft.Consumption/reservationDetails?$filter=properties/usageDate ge 2024-09-12 AND properties/usageDate le 2024-09-12&api-version=2024-08-01"
错误原因
- PowerShell会将字符串中的
$符号解析为变量前缀,导致$filter被错误处理,无法正确传递给API。 Invoke-AzRestMethod的Path参数仅用于传递资源路径,直接拼接查询参数会导致接口对参数的解析逻辑异常。
解决方案
将查询参数拆分到-QueryParameter参数中传递,同时通过转义或单引号避免PowerShell变量解析干扰:
方法一:使用哈希表传递查询参数(推荐)
$requestParams = @{ Method = "GET" Path = "/providers/Microsoft.Capacity/reservationorders/$reservationOrderId/reservations/$ReservationId/providers/Microsoft.Consumption/reservationDetails" QueryParameter = @{ "`$filter" = "properties/usageDate ge 2024-09-12 AND properties/usageDate le 2024-09-12" "api-version" = "2024-08-01" } } Invoke-AzRestMethod @requestParams
方法二:用单引号包裹查询参数值
Invoke-AzRestMethod -Method GET ` -Path "/providers/Microsoft.Capacity/reservationorders/$reservationOrderId/reservations/$ReservationId/providers/Microsoft.Consumption/reservationDetails" ` -QueryParameter @{ '$filter' = 'properties/usageDate ge 2024-09-12 AND properties/usageDate le 2024-09-12' 'api-version' = '2024-08-01' }
关键说明
- 借助
-QueryParameter参数单独传递查询参数,规避路径拼接的解析问题。 - 通过转义符
`或单引号包裹$filter,防止PowerShell将$识别为变量前缀。
内容的提问来源于stack exchange,提问作者yu law
相关产品推荐
相关产品推荐

