且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Invoke-RestMethod的错误处理 - Powershell

更新时间:2022-10-30 11:52:20

这是有点尴尬,但是只要我做的更好,唯一的办法就是不用做更复杂的事情,比如使用.NET的WebRequest和ConvertFrom-Json(或者你所期望的任何数据格式) 。

  try {
Invoke-RestMethod ...你的参数在这里...
} catch {
#挖掘异常以获取响应详细信息。
#注意,value__不是打字错误。
写主机StatusCode:$ _。Exception.Response.StatusCode.value__
写入主机StatusDescription:$ _。Exception.Response.StatusDescription
}


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.

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

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).

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

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
}