如何将CSV导入哈希表并附加重复值?

时间:2017-10-09 14:36:08

标签: powershell csv

假设我有以下CSV文件:

Employee,Software,Manager
Alice,Lorem Ipsum,Bob
Alice,Dolor,Bob
Alice,Sit Amet,Bob
Charlie,Lorem Ipsum,
Charlie,Dolor,
David,Dolor,Stephen

我想要一个像这样的哈希表:

@{
    "Alice" = @{
        "Software" = @("Lorem Ipsum", "Dolor", "Sit Amet");
        "Manager" = "Bob"
    }
};
"Charlie" = @{
    "Software" = @("Lorem Ipsum", "Dolor");
    "Manager" =
}
};
"David" = @{
    "Software" = @("Dolor");
    "Manager" = "Stephen"
}
};

PowerShell中有什么可能的?它将是一个包含另一个哈希表的哈希表,在内部哈希表中我将有一个数组。

3 个答案:

答案 0 :(得分:2)

遍历每个员工,使用软件和经理创建内部哈希表。将其添加到外部哈希表。

$csv =  Import-CSV C:\temp\test.csv
$Employees = $csv.Employee | Select-Object -Unique
$EmployeesHT = @{}
foreach ($Employee in $Employees) {
    $EmployeeDetails = $csv | Where-Object {$_.Employee -eq $Employee}
    $EmployeeHT = @{
        'Software' = $EmployeeDetails.Software
        'Manager' = $EmployeeDetails.Manager | Sort-Object -Unique
    }
    $EmployeesHT.Add($Employee, $EmployeeHT)
}

答案 1 :(得分:1)

您可以循环遍历构建复杂哈希的csv内容:

$arr = Import-Csv file.csv
$dict = @{}
foreach ($emp in $arr) {
    $name = $emp.Employee
    if ($dict.Contains($name)) {
        $dict[$name]["Software"].add($emp.Software)
        if ($emp.Manager -ne "") {
            $dict[$name]["Manager"] = $emp.Manager
        }
    }
    else {
        $dict[$name] = @{"Software"= New-Object System.collections.arraylist;
                          "Manager"= $emp.Manager }
        $dict[$name]["Software"].add($emp.Software)
    }
}

答案 2 :(得分:0)

假设:

$csv = ConvertFrom-CSV -Input @"
Employee,Software,Manager
Alice,Lorem Ipsum,Bob
Alice,Dolor,Bob
Alice,Sit Amet,Bob
Charlie,Lorem Ipsum,
Charlie,Dolor,
David,Dolor,Stephen
"@

构建您的Employees哈希表:

$Employees = @{}
$csv | ForEach {$Employees[$_.Employee] = @{Software = $Employees[$_.Employee].Software, $_.Software | Where {$_}; Manager = $_.Manager}}

结果:

PS C:\> $Employees | ConvertTo-JSON
{
    "Alice":  {
                  "Manager":  "Bob",
                  "Software":  [
                                   {
                                       "value":  "Lorem Ipsum Dolor",
                                       "Count":  2
                                   },
                                   "Sit Amet"
                               ]
              },
    "Charlie":  {
                    "Manager":  "",
                    "Software":  [
                                     "Lorem Ipsum",
                                     "Dolor"
                                 ]
                },
    "David":  {
                  "Manager":  "Stephen",
                  "Software":  "Dolor"
              }
}

注意:您可能会考虑将Manager属性与software属性(意为:Manager = $Employees[$_.Employee].Manager, $_.Manager | Where {$_})类似,以便员工理论上可以拥有多个经理但更重要的是,您不能否决先前记录中经理定义的经理,并在后续记录中显示空值。