来自多个 Excel 列的 PowerShell 散列 table 并进一步使用

PowerShell hash table from multiple Excel columns and use further

我正在读取 Excel 文件的几列并将值存储在散列中。我的 objective 它像

一样进一步使用这个散列
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文件时调用并显示第一个for循环本身的变量,但我也想将它们存储在哈希中table 供以后使用。

您得到该结果是因为您创建的数据结构如下所示(使用 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": ...
        }
    ]
}

要获得所需的结果,您需要创建一个哈希表数组并将其分配给键 "Server",或者如果 "Server" 是您唯一的键,则只需将 $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']
}