字符串到数组或哈希表

String to array or hashtable

我们正在尝试对 Invoke-WebReqeust Cmdlet 进行错误处理。常用的是这样的:

Try {
    # Invoke-WebRequest ....
}
catch {
    $result = $_.Exception.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($result)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Host $responseBody
}

当检测到错误时,将返回以下 String

{ "Error": "AdmConDataError: None (IBDataConflictError: IB.Data.Conflict:MAC address 03:03:33:33:33:36 is used in two fixed addresses 10.20.32.1 and 10.20.32.1, which are in the same network 10.20.32.0/24.)", "code": "Client.Ibap.Data.Conflict", "text": "MAC address 03:03:33:33:33:36 is used in two fixed addresses 10.20.32.1 and 10.20.32.1, which are in the same network 10.20.32.0/24." }

我们现在正在尝试将 String 解析为 Arrayhashtable 以便于使用。期望的结果是:

@{
    Error = 'AdmConDataError: None (IBDataConflictError: IB.Data.Conflict:MAC address 03:03:33:33:33:36 is used in two fixed addresses 10.20.32.1 and 10.20.32.1, which are in the same network 10.20.32.0/24.)'
    Code  = 'Client.Ibap.Data.Conflict'
    text  = 'MAC address 03:03:33:33:33:36 is used in two fixed addresses 10.20.32.1 and 10.20.32.1, which are in the same network 10.20.32.0 / 24.'
}

在其他帖子的帮助下,我们正在考虑重新使用 regexes。但我们似乎无法做到这一点。我们尝试使用 -match '(?<=\")(.*?)(?=\")' 来匹配双引号括号内的所有内容,但这显然是不够的。关于更好的方法有什么想法吗?

示例中的错误字符串有效JSON。

您可以简单地执行 $responseBody | ConvertFrom-Json 以获得具有(在默认方法成员中)三个 NoteProperties 的对象:

  • 代码
  • 错误
  • 文字

返回的字符串看起来很简单 JSON,因此您可以这样转换它:

$resultString = '{ "Error": "AdmConDataError: None (IBDataConflictError: IB.Data.Conflict:MAC address 03:03:33:33:33:36 is used in two fixed addresses 10.20.32.1 and 10.20.32.1, which are in the same network 10.20.32.0/24.)", "code": "Client.Ibap.Data.Conflict", "text": "MAC address 03:03:33:33:33:36 is used in two fixed addresses 10.20.32.1 and 10.20.32.1, which are in the same network 10.20.32.0/24." }'

$result = $resultString | ConvertFrom-Json

当然也可以把这些步骤结合起来,这样更清晰一些。在任何情况下,$result 将包含一个 'PsCustomObject',其属性为 'Error'、'Code' 和 'Text',然后您可以使用通常的语法访问它:

$result.Code
Client.Ibap.Data.Conflict