String to Hashtable

I am making an API call and I get back a string that is

"@{name=xxxx; databaseType=1234} @{name=aaaaa; databaseType=5678}"

This just screams [Hashtable] however ConvertFromStringData is no use here, nor am I able to cast it… Can someone guide how I can convert this string to an array of hashtable or some other datatype that makes sense?

There’s not going to be a completely easy way out, here; you’ll have to do some parsing of that string yourself. It looks similar to PowerShell code, but there are enough differences that you can’t just get away with something like Invoke-Expression. (There’s no comma between the objects, and the values aren’t quoted.)

I would probably take the approach of parsing this string and converting it into a format that can be passed to ConvertFrom-StringData. This is safer than Invoke-Expression, in case the data that comes back is somewhat weird.

Thanks for the speedy reply Dave. I will plug away at it.

Here ya go dude, should work!

("@{name=xxxx; databaseType=1234} @{name=aaaaa; databaseType=5678}".Split('}') -replace "@{","").Trim() | ConvertFrom-StringData

We’re splitting on the close curly brace, to more or less separate these as they should be. Then, stripping away the other characters until we’re left with a key-value pair (line one of my attachment), which is sent to ConvertFrom-StringData (line two).

You should be able to parameterize this snippet easily into your function to get back PowerShell objects from whatever you’re doing.

If you need to go further and separate out the other values, I’d just use a calculated property Select-Object @{Name=‘Column Heading’;Expression={#Code}} syntax to break them out, or make a Custom Object. Let me know if you’d like help with that.

Alright, I had a second coffee break. Here is the PS Object approach to your problem.

$data = "@{name=xxxx; databaseType=1234} @{name=aaaaa; databaseType=5678}"
(($data.Split('}') -replace "@{","").Trim()) | ? Length -gt 0 | ForEach-Object {
    $items = $PSitem.Split(';').Trim()
    
    [pscustomobject]@{Name=$items[0] -replace 'name=';DatabaseType=$items[1] -replace 'databaseType='}}

Result:

Name                                                                                                        DatabaseType                                                                                              
----                                                                                                        ------------                                                                                              
xxxx                                                                                                        1234                                                                                                      
aaaaa                                                                                                       5678