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

查看:253
本文介绍了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
}

另一种选择是使用在从那里复制的代码是:

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

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

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

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

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