Arrays 使用Powershell在多维数组中计数
我在Office365中查询用户,需要根据他们的UserPrincipalName拥有的域计算他们拥有多少许可证。为了使故障排除更容易,我创建了一个新的脚本,只关注问题,但即使在那里我也无法让它工作 这是我的剧本:Arrays 使用Powershell在多维数组中计数,arrays,powershell,Arrays,Powershell,我在Office365中查询用户,需要根据他们的UserPrincipalName拥有的域计算他们拥有多少许可证。为了使故障排除更容易,我创建了一个新的脚本,只关注问题,但即使在那里我也无法让它工作 这是我的剧本: #$users = get-msoluser -TenantId $customer.TenantId -All | Where-Object {$_.islicensed} | Sort-Object UserPrincipalName $users = @( [pscus
#$users = get-msoluser -TenantId $customer.TenantId -All | Where-Object {$_.islicensed} | Sort-Object UserPrincipalName
$users = @(
[pscustomobject]@{
name='User1'
domain='domain1'
license='A'
}
[pscustomobject]@{
name='User2'
domain='domain2'
license='A', 'B'
}
[pscustomobject]@{
name='User3'
domain='domain1'
license='A', 'B'
}
[pscustomobject]@{
name='User4'
domain='domain1'
license='B'
}
[pscustomobject]@{
name='User5'
domain='domain2'
license='A'
}
[pscustomobject]@{
name='User6'
domain='domain1'
license='B'
}
[pscustomobject]@{
name='User7'
domain='domain1'
license='A','B'
}
)
$domains = 'domain1','domain2'
$users |fl *
$domains |fl
$LicenseCounting = @{}
$domains | foreach-object {
$LicenseCounting[$_] = @{}
}
foreach($user in $users)
{
$licenses = @()
$user.license | foreach-object {
$licenses += $_
}
$LicenseCounting[$domains][$licenses] = $LicenseCounting[$domains][$licenses] + 1
}
$LicenseCounting | fl *
<# expected result:
$licenseCounting[domain1][A]=3
$licenseCounting[domain1][B]=4
$licenseCounting[domain2][A]=2
$licenseCounting[domain2][B]=1
#>
在我的例子中,我得到了一个错误。当我使用注释掉的第一行时,它实际上起作用了,但它没有计算,而是将所有许可证放在一个字符串中:例如,“a”、“a”、“B”、“a”。。。等
我确信,一旦在我的示例中使其工作,我也可以使其在实际情况中工作。在分配给哈希表时,您需要引用特定的域和许可证标识符值:
$licenseCount = @{}
foreach($user in $users){
# Create top-level per-domain hashtable for $user.domain if it doesn't already exist
if(-not $licenseCount.ContainsKey($user.domain)){
$licenseCount[$user.domain] = @{}
}
$user.license |ForEach-Object {
# Count each license type separately, store in previously created per-domain hashtable
$licenseCount[$user.domain][$_] += 1
}
}
$licenseCount
现在将填充您文章中描述的信息:
PS ~> $licenseCount['domain2']['A']
2
分配给哈希表时,需要引用特定的域和许可证标识符值:
$licenseCount = @{}
foreach($user in $users){
# Create top-level per-domain hashtable for $user.domain if it doesn't already exist
if(-not $licenseCount.ContainsKey($user.domain)){
$licenseCount[$user.domain] = @{}
}
$user.license |ForEach-Object {
# Count each license type separately, store in previously created per-domain hashtable
$licenseCount[$user.domain][$_] += 1
}
}
$licenseCount
现在将填充您文章中描述的信息:
PS ~> $licenseCount['domain2']['A']
2
谢谢你的回答。在我的示例代码中似乎不起作用,但它可能在我真正需要它的地方起作用,所以我明天回来工作时会通知您+1.同时:编辑不介意它工作,但我有licensecounting,你有LicenseCount,现在也让它在我的工作代码中工作。需要一些调整,但那只是因为我一开始就错了。再次感谢。:)@太酷了,不客气!:)谢谢你的回答。在我的示例代码中似乎不起作用,但它可能在我真正需要它的地方起作用,所以我明天回来工作时会通知您+1.同时:编辑不介意它工作,但我有licensecounting,你有LicenseCount,现在也让它在我的工作代码中工作。需要一些调整,但那只是因为我一开始就错了。再次感谢。:)@太酷了,不客气!:)