Invoke-Restmethod:如何获取返回码? [英] Invoke-Restmethod: how do I get the return code?

查看:32
本文介绍了Invoke-Restmethod:如何获取返回码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PowerShell 中调用 Invoke-RestMethod 时,有没有办法将返回码存储在某处?

Is there a way to store the return code somewhere when calling Invoke-RestMethod in PowerShell?

我的代码如下所示:

$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/Adventure?key=MyKeyGoesHere"

$XMLReturned = Invoke-RestMethod -Uri $url -Method Get;

我在 $XMLReturned 变量中没有看到返回码 200.在哪里可以找到该返回码?

I don't see anywhere in my $XMLReturned variable a return code of 200. Where can I find that return code?

推荐答案

您有几个选择.选项 1 位于此处.它从异常中找到的结果中提取响应代码.

You have a few options. Option 1 is found here. It pulls the response code from the results found in the exception.

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 此处.

Another option is to use the old invoke-webrequest cmdlet found here.

从那里复制的代码是:

$resp = try { Invoke-WebRequest ... } catch { $_.Exception.Response }

您可以尝试以下两种方法.

Those are 2 ways of doing it which you can try.

这篇关于Invoke-Restmethod:如何获取返回码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆