【发布时间】:2020-12-21 12:37:01
【问题描述】:
我正在研究在 powershell 中使用哈希表作为查找表的项目。
在其最简单的形式中,它类似于下面的示例。
示例 1
$hashTable = @{
Key1 = 'Value1'
Key2 = 'Value2'
}
foreach($key in $hashTable.Keys)
{
$value = $hashTable.$key
Write-Output "$key : $value"
}
示例 2
$ageList = @{}
$key = 'Kevin'
$value = 36
$ageList.add( $key, $value )
$ageList.add( 'Alex', 9 )
foreach($key in $ageList.keys)
{
$message = '{0} is {1} years old' -f $key, $ageList[$key]
Write-Output $message
}
我定义了一个类似于下面的多键哈希,与上面的示例相比,它稍微复杂一些。
$x = (1,"Server1",3,1),(4,"Server2",6,2),(3,"Server3",4,3)
$k = 'serverid','servername','locationid','appid' # key names correspond to data positions in each array in $x
$h = @{}
For($i=0;$i -lt $x[0].length; $i++){
$x |
ForEach-Object{
[array]$h.($k[$i]) += [string]$_[$i]
}
}
$all_server_ids = $h['Serverid']
foreach ($server_id in $all_server_ids)
{
$message = 'ServerID {0} has a servername of {1}' -f $server_id, $h[$server_id]
write-output $message
}
根据我的阅读,我知道我可以使用 serverid 作为访问其他值的键。 当我运行上述内容时,我得到的是这个。
ServerID 1 has a servername of
ServerID 4 has a servername of
ServerID 3 has a servername of
在进一步研究中,我尝试使用 GetEnumerator,如下例所示。这不是我想要达到的目标。
$h.GetEnumerator() | % { $_.Value }
我想使用 foreach 的原因是,稍后我可以在循环运行时添加并行工作流来加快处理速度。我希望这种方法没有问题。
我也对创建自定义对象的想法持开放态度,如果这可行的话,它需要能够像下面这样将数组传递给它以创建自定义对象并使用 foreach 循环遍历每个项目。
$x = (1,"Server1",3,1),(4,"Server2",6,2),(3,"Server3",4,3)
【问题讨论】:
-
命名键在哈希表中,而不是在使用位置索引的数组中。要使这个示例正常工作,您需要访问与每个 serverid 的位置相对应的 servername 数组的索引位置 ->
$message = 'ServerID {0} has a servername of {1}' -f $server_id, $h["servername"][$all_server_ids.indexof($server_id)] -
非常感谢非常有用的解释和解决方案。如何存储在特定变量中。
$severid = {0} -f $server_id $servername = {1} -f $h["servername"][$all_server_ids.indexof($server_id)] $locationid = {2} -f $h["locationid"][$all_server_ids.indexof($server_id)]
标签: powershell