Invoke-RestMethod 的错误处理 - Powershell [英] Error Handling for Invoke-RestMethod - Powershell

查看:38
本文介绍了Invoke-RestMethod 的错误处理 - Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 Skytap API (REST) 的 powershell 脚本.如果有错误,我想捕获错误,并尝试显示它.

I have a powershell script using the Skytap API (REST). I would like to catch the error, if there is one, and try to display it.

例如,我们正在更改 IP:

For example, we are changing the IP:

Invoke-RestMethod -Uri https://cloud.skytap.com/configurations/XXXXXX/vms/YYYYYY/interfaces/ZZZZZZ?ip=10.0.0.1 -Method PUT -Headers $headers

如果该 IP 用于其他地方,我将收到 409 冲突错误(请求格式正确,但与其他资源或权限冲突).

If the IP is used somewhere else, I will get the 409 Conflict Error (Request is well-formed but conflicts with another resource or permission).

我想检查错误是否是 409,然后告诉它做其他事情.

I would like to check if the error is 409 and then tell it to do something else about it.

推荐答案

这有点尴尬,但据我所知,这是唯一的方法,无需做更复杂的事情,比如使用 .NET 的 WebRequest 和 ConvertFrom-Json(或其他您期望的数据格式).

This is somewhat awkward but the only way to do it as far as I know without doing something more complicated like using .NET's WebRequest and ConvertFrom-Json (or whatever data format you are expecting).

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-RestMethod 的错误处理 - Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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