我正在读取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文件时,我总是可以首先在for循环本身中调用并显示变量,但我也想将它们存储在哈希表中以备后用。
答案 0 :(得分: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": ...
}
]
}
要获得理想的结果,您需要创建一个哈希表数组并将其分配给键“ 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']
}