powershell - 如何在 PowerShell 数组中反转横向

标签 powershell reverse traversal

给定一个类似于以下内容的 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/

相关文章:

PHP 抓取 txt 文件中的最后 15 行

JAVA - 没有临时字符串、数组、Stringbuilder、子字符串的反向字符串

mysql - 简化mysql递归查询

windows - 通过 Add-PrinterPort PowerShell 命令添加 IPP 端口?

Powershell 按特定所有者列出文件

javascript - 从 yyyy/mm/dd 到 dd/mm/yyyy 的反向日期 javascript

jquery - 在 jQuery 中向上遍历 9 层

c# - 将嵌套的 JSON 转换为简单的 JSON

regex - 在powershell中获取文件名中正则表达式的索引

powershell - 在NAnt构建系统中使用PowerShell Cmdlet的好方法是什么?