Splitting a string the weird way

I love using JSON, as Powershell can really good handle it from scratch and you need it a lot if handling Rest-APIs.
So basically when I stumbled across an issue to seperate s specific string into values, I wondered if JSON could help me.
The string basically is looking like: „CLIENTNAME=aaaaaa&CLIENTADDRESS=10.10.10.10“ (the more versatile users under you might recognize the CS-URI-QUERY of Citrix Workspace App).

So whats the challenge?
I want to parse this string and even if there is more information inside like „Blahblah=uusudfu“, I only want Clientname and Address information.

This is my solution with using JSON:

$inputvalue="CLIENTNAME=aaaaaa&CLIENTADDRESS=10.10.10.10"

$Result="{`"$($inputvalue -replace '=','":"' -replace '&','","')`"}" | ConvertFrom-Json
$Result

What is the output of this?

IP          ClientName
--          ----------
10.10.10.10 aaaaaa

Here we have a very nice PS-Object.

Now, what did I do?
I added to the string the brackets around it to make it a JSON and then replaced all delimiters by the approriate values. The Output looks like this after the replaces and the adding ot {} and before the ConvertFrom-Json:

{"CLIENTNAME":"aaaaaa","CLIENTADDRESS":"10.10.10.10"}

kind of weird way, but this code has for my usage a lot of advantages:

1. The value-pairs can be in any order, so „CLIENTNAME=aaaaaa&CLIENTADDRESS=10.10.10.10“ or „CLIENTADDRESS=10.10.10.10&CLIENTNAME=aaaaaa“
delivers the same output

2. Any additional values that are in the string will be dropped, eg:
„CLIENTNAME=aaaaaa&CLIENTADDRESS=10.10.10.10&USERNAME=jsdfhdjkfhjs&TEST=hgjhggj“

Whats very import: the data has to have the same look, as additional „“ around a value will make this scriptblock break!

Update:

Mathias R. Jessen posted me an even better way on Twitter:

$inputvalue="CLIENTNAME=aaaaaa&CLIENTADDRESS=10.10.10.10"

$Result=$inputvalue -replace '&',"`n" | ConvertFrom-StringData
$Result

This is now really a very short code for doing this job. Thanks Mathias, this is how the powershell community works together!

Dieser Beitrag wurde unter Powershell abgelegt und mit , verschlagwortet. Setze ein Lesezeichen auf den Permalink.