有没有办法Invoke-RestMethod在PowerShell中调用时将返回代码存储在某处?
我的代码看起来像这样:
$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/Adventure?key=MyKeyGoesHere"
$XMLReturned = Invoke-RestMethod -Uri $url -Method Get;
Run Code Online (Sandbox Code Playgroud)
我没有看到我的$XMLReturned变量中的任何地方返回代码为200.我在哪里可以找到返回代码?
Ali*_*ghi 28
你有几个选择.选项1在此处找到.它从异常中找到的结果中提取响应代码.
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
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用此处的旧invoke-webrequest cmdlet .
从那里复制的代码是:
$resp = try { Invoke-WebRequest ... } catch { $_.Exception.Response }
Run Code Online (Sandbox Code Playgroud)
这是你可以尝试的两种方法.
Gri*_*lse 16
所以简短的回答是:你不能。
你应该Invoke-WebRequest改用。
两者非常相似,主要区别在于:
Invoke-RestMethod仅返回响应正文,方便地预先解析Invoke-WebRequest返回完整的响应,包括响应头和状态代码,但不解析响应正文。PS> $response = Invoke-WebRequest -Uri $url -Method Get
PS> $response.StatusCode
200
PS> $response.Content
(…xml as string…)
Run Code Online (Sandbox Code Playgroud)
PowerShell 7 引入了cmdletStatusCodeVariable的参数Invoke-RestMethod。传递不带美元符号 ($) 的变量名称:
$XMLReturned = Invoke-RestMethod -Uri $url -Method Get -StatusCodeVariable 'statusCode'
# Access status code via $statusCode variable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25137 次 |
| 最近记录: |