将冒号分隔的字符串转换为 PowerShell 字典

Convert Colon Separated String to a PowerShell Dictionary

我正在尝试将冒号分隔的字符串转换为 PowerShell 字典。以下是字符串。

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

我在 $inputkeyvalues 变量中有两个键值对,它们由竖线分隔符分隔。 第一个是:Appsetting:true 第二个是:environment:prod

我正在尝试转换为 PowerShell 字典。最终输出应该是这样的,

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

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

有人可以建议我解决这个问题的可能方法吗?提前致谢。

使用 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
}
  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)
        }
   }