Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Colon Separated String to a PowerShell Dictionary

I'm trying to convert Colon Separated String to a PowerShell Dictionary. Following are the strings.

$inputkeyvalues = "Appsetting:true|environment:prod"

I have two key value pairs's in the $inputkeyvalues variable and those are separated by pipe delimiter. first one is: Appsetting:true second one is: environment:prod

and I'm trying to convert to PowerShell dictionary. The final output should be something like,

Key            Value
-----         -----
Appsetting     true
environment    prod

$Dictionary= New-Object "System.Collections.Generic.Dictionary``2[System.String,System.String]"

Can someone please suggest me possible solution for this. Thanks in advance.

like image 225
mahesh Avatar asked Jul 20 '16 00:07

mahesh


1 Answers

Use a hashtable:

$inputkeyvalues = "Appsetting:true|environment:prod"

# Create hashtable
$Dictionary = @{}
# Split input string into pairs
$inputkeyvalues.Split('|') |ForEach-Object {
    # Split each pair into key and value
    $key,$value = $_.Split(':')
    # Populate $Dictionary
    $Dictionary[$key] = $value
}
like image 116
Mathias R. Jessen Avatar answered Oct 13 '22 17:10

Mathias R. Jessen