Invoke-Restmethod:我如何获得返回码?

use*_*342 27 api powershell

有没有办法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)

这是你可以尝试的两种方法.

  • 第一种方法需要一个例外,因此它不适用于提问者获得200响应的情况.`Invoke-WebRequest`是要走的路; 它不是"老"; 它不需要`try` /`catch`或异常.你可能想要编辑一下这个答案,并解释一下`Invoke-RestMethod`只是将内容从JSON自动转换为对象,这可以通过`iwr`将内容传递给`ConvertFrom-Json`来实现. . (9认同)
  • 同时添加了`Invoke-RestMethod`和`Invoke-WebRequest`; 它们都不是替代另一个(如果有什么`iwr`取代`irm',因为它更通用).`irm`是你用`iwr`和`ConvertFrom-Json`做什么的快捷方式,只是让事情变得更快.如果你改进它我会支持你的答案. (8认同)

Gri*_*lse 16

所以简短的回答是:你不能。
你应该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)


Cod*_*ler 6

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)