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=“ (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:


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

What is the output of this?

IP          ClientName
--          ---------- 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:


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=“ or „CLIENTADDRESS=“
delivers the same output

2. Any additional values that are in the string will be dropped, eg:

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


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


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

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.