首页 > 解决方案 > 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答案

标签: powershell

解决方案


ErrorPreference如上面评论中所述,您必须定义Invoke-RestMethodcmdlet 的。这可以通过-ErrorAction参数(并将其值设置为Stop)或通过$ErrorPreference“全局”变量来完成。

来自开发博客

实际上,这意味着如果发生错误并且 Windows PowerShell 可以从中恢复,它将尝试执行下一个命令。但它会通过向控制台显示错误来让您知道发生的错误。

因此,对于non-terminating错误,您必须定义 PowerShell 是停止执行还是继续执行。

下面的代码将 设置ErrorActionStop因此将捕获非终止错误。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 代码。


推荐阅读