powershell - Powershell 问题尝试并捕获
问题描述
PowerShell 新手。我正在使用 Power shell 调用 API 并将响应保存在示例文件中。
它工作正常。挑战是如果 API 遇到一些挑战(Down 等).. 没有响应等,我应该怎么做。在这种情况下,我不想保存我的文件。现在它正在保存带有错误的文件。
尝试了很多尝试和捕获,但无法找到错误代码。
try
{
$uri = "https://my url"
$response = Invoke-RestMethod -Uri $uri
$response.Save("C:\Users\rtf\Desktop\Details\samplet.xml")
Write-Host "done"
}
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
}
上面的代码基于这个 stackoverflow答案。
解决方案
ErrorPreference
如上面评论中所述,您必须定义Invoke-RestMethod
cmdlet 的。这可以通过-ErrorAction
参数(并将其值设置为Stop
)或通过$ErrorPreference
“全局”变量来完成。
来自开发博客:
实际上,这意味着如果发生错误并且 Windows PowerShell 可以从中恢复,它将尝试执行下一个命令。但它会通过向控制台显示错误来让您知道发生的错误。
因此,对于non-terminating
错误,您必须定义 PowerShell 是停止执行还是继续执行。
下面的代码将 设置ErrorAction
为Stop
因此将捕获非终止错误。PowerShell 何时会检测到终止错误,或者什么是终止错误?例如,如果内存不足,或者 PowerShell 检测到语法错误。
由于Invoke-RestMethod文档状态:
Windows PowerShell 根据数据类型格式化响应。对于 RSS 或 ATOM 源,Windows PowerShell 返回项目或条目 XML 节点。对于 JavaScript 对象表示法 (JSON) 或 XML,Windows PowerShell 将内容转换(或反序列化)为对象。
$response
可能包含 PowerShell 尝试解析的 XML 或 JSON(或其他特定内容)。
更新 1:基于以下说明错误消息的评论,$response
其中包含 PowerShell 转换的 XML。最后$response
应该有一个Error status
属性,以防出错。借助Get-Member
我们可以检查是否$response
包含错误属性并执行额外的错误处理。
try
{
$uri = "https://my url"
$response = Invoke-RestMethod -Uri $uri -ErrorAction Stop
# Was a valid response object returned?
if ($null -ne $response) {
# Has the object an REST-API specific Error status property?
if(Get-Member -inputobject $response-name "UnknownResult" -Membertype Properties){
Write-Error "response contains error $response"
Write-Error "$($response.UnknownResult.Error.Message)"
}
else {
# No error detected, save the response
$response.Save("C:\Users\rtf\Desktop\Details\samplet.xml")
Write-Host "done" -ForegroundColor Magenta
}
}
}
catch
{
$_.Exception
}
您可以在此链接下使用 xml 代码。
推荐阅读
- php - BadMethodCallException 方法 Illuminate\Database\Eloquent\Collection::paginate 不存在
- javascript - 将项目放入列表框中 - 在 Angularjs 中说“选择几个月后选择”是什么意思?
- python - 使用 Python bigquery_datatransfer 创建 adwords BigQuery Transfer:错误 400 请求包含无效参数
- c - Is it possible to access/update the child thread's resource from parent thread?
- java - Why do we use matrices?
- intercom - How to create events for a visitor that is already an intercom user?
- linux - sed command is not working properly when using wildcard
- flutter - Flutter ListView in StateLess Widget
- c# - 初始化安装时发生异常:System.BadImageFormatException:无法加载文件或程序集
- node.js - 如何在NodeJS中访问AudioContext并将正弦波写入AudioBuffer