我们正在尝试对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
:
{“错误”:“ AdmConDataError:无(IBDataConflictError:IB.Data.Conflict:MAC地址03:03:33:33:33:36在两个固定地址10.20.32.1和10.20.32.1中使用在里面 同一网络10.20.32.0/24。)”, “ code”:“ Client.Ibap.Data.Conflict”, “ text”:“ MAC地址03:03:33:33:33:36用于两个固定地址10.20.32.1和10.20.32.1,它们位于同一网络10.20.32.0/24中。” }
我们现在正尝试将String
解析为Array
或hashtable
,以便于使用。理想的结果将是:
@{
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 '(?<=\")(.*?)(?=\")'
来匹配双引号括弧之间的所有内容,但这显然是不够的。有更好的方法吗?
答案 0 :(得分:3)
示例中的错误字符串是有效的JSON。
您只需执行$responseBody | ConvertFrom-Json
即可获得具有三个NoteProperty(在默认方法成员中)的对象:
答案 1 :(得分:1)
返回的字符串看起来像简单的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
都将包含一个具有属性'Error','Code'和'Text'的'PsCustomObject',然后您可以使用常规语法对其进行访问:
$result.Code
Client.Ibap.Data.Conflict