多查询Powershell阵列

时间:2019-11-15 15:31:13

标签: arrays powershell

具有包含组织数据的数组 像这样:

org_id  org_name        parent_id
1       Company         NULL        
2       HR              1           
3       MARKETING       2           
4       FINANCE         1           
5       IT              4           

所以结构是:

[Company]
|- HR
| |- MARKETING
|- FINANCE
| |- IT

我试图弄清楚如何查询组织针对特定用户的上级组织。

因此,如果用户定义他们属于IT,我想匹配org_name中的字符串并获取parent_id。然后将parent_id与org_id匹配,以便最终获得org_name,在本例中为FINANCE。

2 个答案:

答案 0 :(得分:2)

如果我对问题的理解正确,则您的组织结构如下:

$Company = [PsCustomObject]@{ org_id = 1; org_name = 'Company'; parent_id = $null },
           [PsCustomObject]@{ org_id = 2; org_name = 'HR'; parent_id = 1 },
           [PsCustomObject]@{ org_id = 3; org_name = 'MARKETING'; parent_id = 2 },
           [PsCustomObject]@{ org_id = 4; org_name = 'FINANCE'; parent_id = 1 },
           [PsCustomObject]@{ org_id = 5; org_name = 'IT'; parent_id = 4 }

您可以这样做

$department = 'IT'
$parentId   = ($Company | Where-Object { $_.org_name -eq $department}).parent_id
$orgName    = ($Company | Where-Object {$_.org_id -eq $parentId }).org_name

此后,$orgName包含FINANCE

如果您所在的部门是HRFINANCE,它将返回Company
如果您搜索部门MARKETING,您将得到HR

答案 1 :(得分:0)

使用此Join-Object cmdlet(另请参见:what's the best way to join two tables into one?),您可以利用其自连接功能创建交叉引用:

$List = ConvertFrom-SourceTable '
    org_id  org_name        parent_id
    1       Company         NULL
    2       HR              1
    3       MARKETING       2
    4       FINANCE         1
    5       IT              4' # https://www.powershellgallery.com/packages/ConvertFrom-SourceTable

$Reference = FullJoin $List parent_id -eq org_id '', 'parent'
$Reference | Format-Table # Show what's in the $Reference

org_id org_name  parent_id parentorg_id parentorg_name parentparent_id
------ --------  --------- ------------ -------------- ---------------
1      Company   NULL
2      HR        1         1            Company        NULL
3      MARKETING 2         2            HR             1
4      FINANCE   1         1            Company        NULL
5      IT        4         4            FINANCE        1
                           3            MARKETING      2
                           5            IT             4

选择组织的上级组织:

$Organization = 'IT'
($Reference | Where-Object org_name -eq $Organization).parentorg_name
FINANCE

反之亦然:选择上级组织的组织:

$Parent = 'Company'
($Reference | Where-Object parentorg_name -eq $Parent).org_name
HR
FINANCE