给定一个类似于以下内容的 PowerShell array 哈希表1:
$dept= @{
'Sales' = @{
'SAM' = 'Manager'
'SAP' = 'Person'
}
'IT' = @{
'ITM' = 'Manager'
'ITS' = 'Specialist'
'ITT' = 'Technician'
'ITC' = 'Consultant'
}
}
如果在控制台输入以下内容:
$dept.it.itc
$dept.sales.sam
我得到:
Consultant
Manager
这符合预期。
但是,我想做的是这样的
write-host $dept.itc
write-host $dept.sam
并得到
IT Consultant
Sales Manager
作为返回。
我正在寻找一个排序函数来对数组进行“反向遍历”,因为“IT”、“销售”等是我需要将新用户放入的 OU。为了简洁起见,我删除了更多 OU。
[1]数组只是一个值列表,哈希表是类似于 Javascript 的 JSON 的键/值对的集合或 Python 的 dict
。
最佳答案
值得注意的是,您的对象不是Array
。在 PowerShell 中,@{}
是一个哈希表
。您可以阅读有关使用哈希表的更多信息 here .
如果您的部门 OU 中的每个角色都有我所说的唯一角色代码,那么您所需要做的就是匹配嵌套中的Key
哈希表来查找您的部门。创建一个快速帮助函数来处理多个调用是最简单的,除非您只是循环遍历数组或字符串列表。
以下是如何提取所需字符串的示例:(如果您没有唯一键,那么您可能需要添加额外的过滤)
$Departments = @{
'Sales' = @{
'SAM' = 'Manager'
'SAP' = 'Person'
}
'IT' = @{
'ITM' = 'Manager'
'ITS' = 'Specialist'
'ITT' = 'Technician'
'ITC' = 'Consultant'
}
}
function Get-DepartmentOU {
Param (
[CmdletBinding()]
[Parameter(Mandatory = $true)]
[System.String]
$RoleCode
)
# Get the DictionaryEntry in the main Hashtable where the nested Hashtable value matches the role you are looking for.
$Department = $script:Departments.GetEnumerator() | Where-Object { $_.Value.ContainsKey($RoleCode) }
# Print the name of the DictionaryEntry (Your department) and retrieve the value from the Hashtable for the role.
Write-Output ("{0} {1}" -f $Department.Name, $Department.Value[$RoleCode])
}
然后您可以通过运行该函数并指定代码来获取它们。
PS > Get-DepartmentOU -RoleCode ITC
IT Consultant
关于powershell - 如何在 PowerShell 数组中反转横向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71888502/