Reputation: 478
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.
Upvotes: 7
Views: 7260
Reputation: 4253
I stripped the @{ and } characters of the string then created the dictionary key value pairs.
$totalDict=@{}
Foreach ($itemDictString in $tempObj.tag_instances)
{
$Dictionary=@{}
$itemDictString.Replace('@{','').Replace('}','').Split(';') | ForEach-Object{
$key,$value=$_.Split('=').Trim()
$Dictionary[$key]=$value
}
$key="tag_id"
$composite_key="$($tempObj.first_name) $($tempObj.last_name) $($tempObj.id) $($Dictionary[$key])"
Write-Host $composite_key
if($totalDict.ContainsKey($composite_key) -eq $true)
{
$totalDict[$composite_key]=$totalDict[$composite_key]+1
}
else
{
$totalDict.Add($composite_key,1)
}
}
Upvotes: 0
Reputation: 174920
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
}
Upvotes: 9