Question
PowerShell 7+ parse querystring-style strings into HashTable
I'm trying to avoid the apparent mess that is the .NET Core querystring parsing classes for now, yes.
For a given string: $data = 'id=1&name=neil&language=powershell'
I'd like to get a hashtable that looks like this:
@{
id = 1
name = 'neil'
language = 'powershell'
}
I've tried this:
$data -split '&' | ConvertFrom-StringData
But I actually get an array of hashtables because ConvertFrom-StringData
wants a single newline-separated string. So I tried this:
$data -replace '&','`n' | ConvertFrom-StringData
Which is yucky, but also doesn't work.
Before I end up writing a for
loop, is there a more PowerShell-idiomatic way to do this?
EDIT:
While waiting I've ended up doing this, but I don't like it:
$ht = @{}
$data -split '&' |
ForEach-Object {
$kvp = $_ -split '='
$ht[$kvp[0].Trim()] = if ($kvp.Length -gt 1) { $kvp[1].Trim() } else { $null }
}
EDIT 2:
I fixed my error where I'd incorrectly put a backslash instead of backtick as my escape character. I'd done the correct thing in my actual test, but re-typed incorrectly into this question. Sorry for the confusion.