powershell如何将项目添加到字典,然后将该列表中的项目添加到另一个字典?

时间:2017-01-27 17:31:22

标签: powershell

我正在尝试解析XML文件中的值,该文件将使用foreach循环将项添加到集合中,然后使用带有附加值的另一个foreach循环将该集合中的项添加到另一个集合中。这就是我到目前为止所做的事情:

[xml]$testResults = Get-Content -Path $testResultsPath
$resultsByName = @{}
$resultsByPhone = @{}
$loop = 0
foreach($testCase in $testResults.'test-results'.'test-suite')
{
    foreach($testCase in $testResults.'test-results'.'test-suite'[$loop].'results'.'test-suite'.'results'.'test-suite'.'results'.
    'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-suite'.'results'.'test-case')
    {
    $NameWithPone = $testCase.name.ToUpper().Substring($testCase.name.LastIndexOf('.')+1);  
    $Name =$NameWithPone.Substring(0, $NameWithPone.IndexOf('_'));
    $PhoneVersion = $testCase.name.Substring($testCase.name.IndexOf('_')+1);
    $resultsByName.Add($PhoneVersion, $Name)
        Foreach($resultCase in $resultsByName)
        {
            $resultsByPhone.Add($resultsByName, $testCase.result)
        }
    }
$loop++
}

但是这只会添加第一个结果,然后给出错误"Item has already been added. Key in dictionary: 'System.Collections.Hashtable' Key being added: 'System.Collections.Hashtable'"我认为这是因为我每次都添加相同的项目,我该怎么纠正呢?

第一个集合将如下所示:

google_pixel_xl-7_1_1          TESTTHATAREGISTEREDUSERCANLOGINTOTHECUSTOMERAPPSUCCESSFULLY                 
htc_10-6_0_1                   TESTTHATAREGISTEREDUSERCANLOGINTOTHECUSTOMERAPPSUCCESSFULLY                 
oneplus_one-4_4_4              TESTTHATAREGISTEREDUSERCANLOGINTOTHECUSTOMERAPPSUCCESSFULLY  

但我想将两个值一起添加到另一个集合中,如下所示:

google_pixel_xl-7_1_1 TESTTHATAREGISTEREDUSERCANLOGINTOTHECUSTOMERAPPSUCCESSFULLY Error

1 个答案:

答案 0 :(得分:0)

我通过这样做完成了这个:

[xml]$testResults = Get-Content -Path $testResultsPath
foreach($testCase in $testResults.'test-results'.'test-suite')
{
    function Get-TestCases($myResults)
    {
        $testCases = @()
        foreach($child in $myResults.ChildNodes)
        {
            if($child.'test-case' -eq $null)
            {
                foreach($testCase in Get-TestCases $child)
                {
                    $testCases += $testCase     
                }
            }
            else
            {
                $testCases += $child.'test-case'
            }
        }
        return $testCases
    }
    $tests = Get-TestCases $testResults.'test-results'.'test-suite'[$loop]
    foreach($test in $tests)
    {
         $PhoneVersion = $test.name.Substring($test.name.IndexOf('_')+1);

         $resultsByPhone.Add($PhoneVersion, @{})
         $NameWithPhone = $test.name.ToUpper().Substring($test.name.LastIndexOf('.')+1);    
         $Name =$NameWithPhone.Substring(0, $NameWithPhone.IndexOf('_'));

         $resultsByPhone[$phoneVersion].Add($Name, $test.result)           


    }
    $resultsByPhone[$phoneVersion] 
    $resultsByPhone
    $loop++
}
相关问题