从一个SonarAPI调用中,获得日期值为2018-12-13T18:04:42-0500
,
现在,当尝试将此日期值解析为SonarAPI时,其失败并出现以下错误:
Invoke-RestMethod : {
"errors": [
{
"msg": "Date '$date' cannot be parsed as either a date or date+time"
}
]
}
在浏览器上浏览以下URL时:
https://xxx.xxx.xxxx/api/measures/search_history?component=AP-EASI&metrics=coverage&from=2018-12-13T18:04:42-0500&to=2018-12-13T18:04:42-0500
浏览器上的输出为:
{
"paging": {
"pageIndex": 1,
"pageSize": 100,
"total": 1
},
"measures": [
{
"metric": "coverage",
"history": [
{
"date": "2018-12-13T18:04:42-0500",
"value": "0.0"
}
]
}
]
}
$date = "2018-12-13T18:04:42-0500"
$Result = Invoke-RestMethod -Method Get -Uri 'https://xxx.xxx.xxx/api/measures/search_history?component=AP-EASI&metrics=coverage&from=$date&to=$date' -Headers $Headers | ConvertTo-Json -Depth 10
Write-host "$Result"
答案 0 :(得分:2)
如果您在代码中使用单引号,则会传递确切的字符串,因此不会将变量“转换”为它们的值。
使用该代码:
$Result = Invoke-RestMethod -Method Get -Uri 'https://xxx.xxx.xxx/api/measures/search_history?component=AP-EASI&metrics=coverage&from=$date&to=$date' -Headers $Headers
您访问该URL:
https://xxx.xxx.xxx/api/measures/search_history?component=AP-EASI&metrics=coverage&from=$date&to=$date
您应该做的是使用双引号"
,以便对变量求值。您应该使用的代码是:
$Result = Invoke-RestMethod -Method Get -Uri "https://xxx.xxx.xxx/api/measures/search_history?component=AP-EASI&metrics=coverage&from=$date&to=$date" -Headers $Headers
假设您的$Headers
值正确,那应该可以。
注意:正如vonPryz在评论中建议的那样,请务必记住发布您的代码,因为这对于故障排除至关重要(如您所见)。