use*_*230 21 rest error-handling http powershell-4.0
我有一个使用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
Run Code Online (Sandbox Code Playgroud)
如果在其他地方使用IP,我将得到409冲突错误(请求格式正确,但与其他资源或权限冲突).
我想检查错误是否为409,然后告诉它做一些其他事情.
Dav*_*son 53
这有点尴尬,但据我所知,只有使用.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
}
Run Code Online (Sandbox Code Playgroud)
MeG*_*Guy 12
我知道您要求使用 Powershellv4,但从 v6/v7 开始:
Try {
$WebRequestResult = Invoke-RestMethod -Uri $URL -Headers $Headers -Body $BodyJSON -Method $Method -ContentType $ContentType -SkipCertificateCheck
} Catch {
if($_.ErrorDetails.Message) {
Write-Host $_.ErrorDetails.Message
} else {
Write-Host $_
}
}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ohn 12
Powershell 7 引入了-SkipHttpErrorCheck参数。这指示 cmdlet 的行为方式与编程框架中的 Web 请求类似(即,其中 404、409 等是有效响应 - Web 请求成功,但服务器返回错误代码)。
这可以与-StatusCodeVariable参数结合使用。这指示 cmdlet 将响应代码插入到变量中。但是,变量名称作为字符串传递(而不是作为引用)。例如:
$scv = $null
Invoke-RestMethod ... -SkipHttpErrorCheck -StatusCodeVariable "scv"
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27168 次 |
最近记录: |