在PowerShell中调用Invoke-RestMethod时,有没有办法将返回代码存储在某个地方?
我的代码如下所示:
$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/Adventure?key=MyKeyGoesHere"
$XMLReturned = Invoke-RestMethod -Uri $url -Method Get;我没有在我的$XMLReturned变量中看到返回码200。我在哪里可以找到返回代码?
发布于 2016-07-28 04:28:05
你有几个选择。选项1是found here。它从异常中发现的结果中提取响应代码。
try {
Invoke-RestMethod ... your parameters here ...
} catch {
# Dig into the exception to get the Response details.
# Note that value__ is not a typo.
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription
}另一种选择是使用旧的invoke-webrequest cmdlet找到here。
从那里复制的代码如下:
$resp = try { Invoke-WebRequest ... } catch { $_.Exception.Response }这是你可以尝试的两种方法。
发布于 2020-10-08 19:42:17
所以简短的答案是:你不能。
您应该改用Invoke-WebRequest。
两者非常相似,主要区别在于:
Invoke-RestMethod只返回响应体,方便的是pre-parsedInvoke-WebRequest返回完整的响应,包括响应头和状态代码,但不解析响应体。PS> $response = Invoke-WebRequest -Uri $url -Method Get
PS> $response.StatusCode
200
PS> $response.Content
(…xml as string…)发布于 2021-03-02 11:04:59
Invoke-WebRequest将解决您的问题
$response = Invoke-WebRequest -Uri $url -Method Get
if ($response.StatusCode -lt 300){
Write-Host $response
}如果您愿意,请尝试接听电话
try {
$response = Invoke-WebRequest -Uri $url -Method Get
if ($response.StatusCode -lt 300){
Write-Host $response
}
else {
Write-Host $response.StatusCode
Write-Host $response.StatusDescription
}
}
catch {
Write-Host $_.Exception.Response.StatusDescription
}https://stackoverflow.com/questions/38622526
复制相似问题