我有一个使用 Skytap API (REST) 的 powershell 脚本。我想捕获错误(如果有)并尝试显示它。
比如我们在换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 冲突错误(请求格式正确但与其他资源或权限冲突)。
我想检查错误是否为 409,然后告诉它做一些其他事情。
最佳答案
这有点尴尬,但据我所知,这是唯一的方法,无需执行更复杂的操作,例如使用 .NET 的 WebRequest 和 ConvertFrom-Json(或您期望的任何数据格式)。
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
}
关于rest - Invoke-RestMethod 的错误处理 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613572/