首页 > 解决方案 > 为什么将新值添加到 Hashmap 中的现有键会连接值,但前提是它是在循环中完成的

问题描述

我的目标是读取如下所示的配置文件:

#This is a comment and ignored
[Section, gets ignored too]
key=value
animal=cat, dog
path="C:\Programm Files\", "C:\New Folder"
foo=bar

我想将这些值放入一个哈希图中,其中的值是一个看起来像这样的列表

Name                Value
---                 ---
key                 {value}
animal              {cat, dog}
path                {"C:\Programm Files\", "C:\New Folder"}
foo                 {bar}

我的代码运行良好,但是,它没有添加 dog 或 "C:\New Folder" 作为第二个值,而是将其添加为串联。但是,在控制台中添加值确实有效:

$fileContent.animal.Count
>>1

$fileContent.path.Count
>>1

$fileContent
>>Name                Value
---                 ---
key                 {value}
animal              {cat dog}
path                {"C:\Programm Files\" "C:\New Folder"}
foo                 {bar}

$fileContent.path.Add("Test")
$fileContent.path.Count
>> 2
$fileContent
>>Name                Value
---                 ---
path                {"C:\Programm Files\" "C:\New Folder", Test}

我的代码看起来像这样

foreach ($line in $fileRawContent)
{
    #if it doesn't start with # or [ continiue
    if(-not ($line.StartsWith("#") -or $line.StartsWith("[")))
    {          
        #Split string. Key always is on Position 0
        $content = $line.Split("=")
        $key = $content[0]

        #If Values with ',' are present, split again
        if($content[1].Contains(","))
        {
            $content = $content.Split(",")
            #$content = $content.Trim()
            
            #Add the contents to the values
            for($i = 1; $i -lt $content.Count; $i++)
             {
                    $value += $content[$i]
             }
        }
        #if no comma is present, it's a 1:1 link
        else {$value = $content[1]}

        #generate List on the key value
        $fileContent.$key = [System.Collections.Generic.List[string]]::new()

        #if only one value is present no running through an array is neccessary
        if($value.GetType().Name -eq "String")
        {
            $fileContent.$key.Add($value)
        }
        else
        {
            foreach($item in $value)
            {
                $fileContent.$key.Add($item)
            }
        }
    }

    #setting everything on null since the scope of powershell variables is global
    $content = $null
    $key = $null
    $value = $null
}

我的错误在哪里?

标签: .netpowershellhashmap

解决方案


看看这是否有帮助。它将为包含多个值的任何元素创建一个数组,并将每个元素添加到一个名为 foo 的对象中。

  1. 创建一个包含数据的对象。我正在使用 GLOBAL 以便在脚本运行后更轻松地在命令行调用 $foo。

.

$GLOBAL:foo = @{}

$fileContents = gc -Path .\dale.txt
foreach($row in $fileC) {
      $propertyName,$propertyValue = $row

      # Converts to an array if contains comma separated string
      $propertyValue = $propertyValue.Split(",").trim()        
      $foo.$propertyName = $propertyValue
}

运行脚本,然后键入 $foo 以查看对象内容 $foo.Animal.GetType() 将与 Path 一起成为一个数组。所有其他值将是字符串


推荐阅读