Search code examples
regexpowershellwebrequest

String to array or hashtable


We're trying to do error handling on the Invoke-WebReqeust Cmdlet. What is commonly used is something like this:

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
}

When an error is detected the following String will be returned:

{ "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." }

We're now trying to parse the String to an Array or a hashtable for ease of use. The desired result would be:

@{
    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.'
}

With the help of other posts we were thinking about falling back on regexes. But we can't seem to get it right. We tried with -match '(?<=\")(.*?)(?=\")' to match everything between double quoted brackets, but that's clearly not sufficient. Any ideas on a better approach?


Solution

  • The error string in the example is valid JSON.

    You can simply do $responseBody | ConvertFrom-Json to obtain an object with (among the default method members) three NoteProperties:

    • code
    • Error
    • text