来自多个Excel列的PowerShell哈希表并进一步使用

问题描述 投票:0回答:1

我正在阅读Excel文件的几列并将值存储在哈希中。我的目标是进一步使用这个哈希

Hostname: $computer['server']['hostname']         # Hostname: host1
IP: $computer['server']['ip']                     # IP: x.x.x.x
Environment: $computer['server']['Environment']   # Environment: production

代码段:

$computers = @{}
$computers['Server'] = @{}
$computers['Server']['Hostname'] = @()
$computers['Server']['Environment'] = @()
$computers['Server']['ip'] = @()   

for ($startRow=2; $startRow -le $rowCount; $startRow++) {
    $hostname = $workSheet.Cells.Item($startRow,2).Value()
    $environment = $workSheet.Cells.Item($startRow,1).Value()
    $pip = $workSheet.Cells.Item($startRow,4).Value()
    $sip = $workSheet.Cells.Item($startRow,5).Value()

    $computers['Server']['Hostname'] += $hostname
    $computers['Server']['Environment'] += $environment
    $computers['Server']['ip'] += $ip
}

foreach ($computer in $computers) {
    foreach ($server in $computer['Server']) {
        $myhost = $computer['Server']['Hostname']
        $environ = $computers['Server']['Environment']

        Write-Host "$myhost : $environ `n"  
    }    
}

实际产量:

host1 host2 host3 host4 : prod dev prod stag

预期产量:

host1: prod
host2: dev
host3: prod
host4: stag

编辑注意:我总是可以在读取Excel文件时首先调用并显示变量,然后我还想将它们存储在哈希表中供以后使用。

powershell multidimensional-array hashtable powershell-v2.0 powershell-v3.0
1个回答
2
投票

您得到的结果是因为您创建的数据结构如下所示(使用JSON表示法):

{
    "Server": {
        "Hostname": [ "host1", "host2", "host3", "host4" ],
        "Environment": [ "prod", "dev", "prod", "stag" ],
        "IP": [ ... ]
    }
}

当你真正想要这样的东西:

{
    "Server": [
        {
            "Hostname": "host1",
            "Environment": "prod",
            "IP": ...
        },
        {
            "Hostname": "host2",
            "Environment": "dev",
            "IP": ...
        },
        {
            "Hostname": "host3",
            "Environment": "prod",
            "IP": ...
        },
        {
            "Hostname": "host4",
            "Environment": "stag",
            "IP": ...
        }
    ]
}

要获得所需的结果,您需要创建一个哈希表数组并将其分配给关键字“服务器”,或者只是将“服务器”作为唯一的密钥使$computers成为一个数组:

$computers = @(for ($startRow=2; $startRow -le $rowCount; $startRow++) {
    ...

    @{
        'Hostname'    = $hostname
        'Environment' = $environment
        'IP'          = $ip
    }
})

然后,您可以枚举这样的计算机:

foreach ($computer in $computers) {
    '{0}: {1}' -f $computer['Hostname', 'Environment']
}

或者你可以使$computers成为哈希的散列

$computers = @{}
for ($startRow=2; $startRow -le $rowCount; $startRow++) {
    ...

    $computers[$hostname] = @{
        'Environment' = $environment
        'IP'          = $ip
    }
})

并枚举这样的主机:

foreach ($computer in $computers.GetEnumerator()) {
    '{0}: {1}' -f $computer.Key, $computer.Value['Environment']
}
© www.soinside.com 2019 - 2024. All rights reserved.