Import-CSV嵌套HashTable

时间:2018-01-26 01:54:06

标签: powershell

说我有一个类似的CSV文件:

arch,osversion,kb
32,6.1,KB1,http://kb1
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4

如何将此CSV导入到看起来像这样的结构化哈希表中?

32 -> 6.1 -> KB1 -> http://kb1
   -> 6.2 -> KB2 -> http://kb2
64 -> 6.1 -> KB3 -> http://kb3
   -> 6.2 -> KB4 -> http://kb4

以下命令会产生http://kb1

$data['32'].'6.1'.'KB1'

2 个答案:

答案 0 :(得分:0)

可能Group-Object就是你想要的。

$csv = @'
arch,osversion,kb,link
32,6.1,KB1,http://kb1
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4
'@

$data = ConvertFrom-Csv $csv

$data | Group-Object -Property arch

或者更接近您想要查询的内容:

$groups = $data | Group-Object -Property arch, osversion, kb
($groups | ? Name -eq '32, 6.1, KB1').Group.link

你甚至可以使用变量...

$a = '32'
$o = '6.1'
$k = 'KB1'

($groups | ? Name -eq "$a, $o, $k").Group.link

由此,您可以确定这种模式是否适合您。

答案 1 :(得分:0)

有趣的任务。以下代码段可以提供帮助(解决arch重复项):

Remove-Variable data*, aux* -ErrorAction SilentlyContinue ### clear for debugging purposes
$datacsv = @'
arch,osversion,kb,link
32,6.1,KB1,http://kb1
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4
'@
$datac = ConvertFrom-Csv $datacsv
$datag = @{}
$datac | ForEach-Object {
    $auxLeaf    = @{ $_.kb = $_.link }
    $auxParent  = @{ $_.osversion = $auxLeaf }
    if ( $datag.ContainsKey( $_.arch) ) {
        $auxParent += $datag[ $_.arch]
    }
    $datag.Set_Item( $_.arch, $auxParent )
}

然后,$datag['32']['6.1']['KB1']返回所需的值http://kb1

另一个有趣的问题:解决特定osversion中的arch重复项:

Remove-Variable data*, aux* -ErrorAction SilentlyContinue ### clear for debugging purposes
$datacsv = @'
arch,osversion,kb,link
32,6.1,KB1,http://kb1
32,6.1,KB5,http://kb5
32,6.1,KB7,http://kb7
32,6.2,KB2,http://kb2
64,6.1,KB3,http://kb3
64,6.2,KB4,http://kb4
'@
$datac = ConvertFrom-Csv $datacsv
$datag = @{}
$datac | ForEach-Object {
    $auxLeaf   = @{ $_.kb = $_.link }
    $auxParent = @{ $_.osversion = $auxLeaf }
    if ( $datag.ContainsKey( $_.arch) ) {
        if ( $datag[$_.arch].ContainsKey($_.osversion) ) {
            $auxLeaf  += $datag[$_.arch][$_.osversion]
            $auxParent = @{ $_.osversion = $auxLeaf }
        } else {
            $auxParent += $datag[ $_.arch]
        }
    }
    $datag.Set_Item( $_.arch, $auxParent )
}

后面的代码片段大致相当于

$datag =
@{
    '32' = @{ '6.1' = @{ 'KB1'='http://kb1';
                         'KB5'='http://kb5';
                         'KB7'='http://kb7' };
              '6.2' = @{ 'KB2'='http://kb2' }
            };
    '64' = @{ '6.1' = @{ 'KB3'='http://kb3' };
              '6.2' = @{ 'KB4'='http://kb4' } 
            }
 }