arrays - 创建哈希表,其中键有多个数组值

标签 arrays powershell hashtable

我正在尝试使用 PowerShell 创建一个哈希表,其中键是服务器名称,该服务器名称具有多个值,其中一些是数组。

key = 服务器名称

值(value)观:

ServerID(单个 ID 值)

GroupID(ID 值数组,与下面的特定组名称相关)

GroupName(值数组,与上面数组中的特定组 ID 相关联)

我正在迭代服务器列表并尝试构建它。

$ServerHashTable = @{}
$ServerHashTable.ServerName = @()
$ServerHashTable.ServerID = @()
$ServerHashTable.GroupName = @()
$ServerHashTable.GroupID = @()

$ServerHashTable.ServerName += $ServerName
$ServerHashTable.ServerID += $ServerID
$ServerHashTable.GroupName += $GroupName
$ServerHashTable.GroupID += $GroupID

我遇到的问题是 key 似乎不是服务器名称,并且我不确定在添加 GroupID 和 GroupName 时如何链接它们。

感谢您对此提供的任何帮助

最佳答案

看起来您可能想要使用的数据结构是一个对象,而不是一个键/值(单数)的哈希表。

$ServerName = 'ExampleServerName'
$ServerID = 12345
$GroupName = @('ExampleGroup1','ExampleGroup2')
$GroupIDs = @(1,2,3)

$Servers = @()
$Servers += [pscustomobject]@{
    ServerName = $ServerName
    ServerID   = $ServerID
    GroupName  = $GroupName
    GroupID    = $GroupID
}

然后您可以使用Where-Object来过滤名称

$Servers | Where-Object {$_.ServerName -eq 'ExampleServerName'}

请注意,[pscustomobject] 类型加速器是版本 3 或更高版本。早期版本需要使用New-Object

关于arrays - 创建哈希表,其中键有多个数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50359533/

相关文章:

python - 将字符串转换为 numpy 数组

c++ - 索引 3-D 数组中的元素

powershell - 替换字符串中的第一个字符

algorithm - 散列时预期的空槽数

c++ - 创建更好的哈希函数

javascript - 排序超过 10 行的 HTML 表格不起作用

arrays - Matlab 将向量转换为二进制矩阵

powershell - 哪个版本的 PowerShell 修复了 "whatif"传播?

powershell - 按属性名称过滤 cim 实例类

java - 将通用类型 <T> 的元素添加到 LinkedList 的 arrayList