PowerShell哈希表的关键问题

时间:2015-04-16 03:39:42

标签: powershell hashtable

也许我做错了,但是当我尝试使用密钥引用哈希表成员时,我没有得到任何结果,但是当我使用相同的密钥过滤.GetEnumerator()输出时,我得到了一个结果。

这不起作用:

$year = "2015"
$msol_year_members_table = @{}
foreach ($member in $(Get-MsolGroupMember -GroupObjectId $(Get-MsolGroup | ?{ $_.DisplayName -eq $("Class of " + $year) }).ObjectId)) {
    $msol_year_members_table[$member.ObjectId] = $member
}

foreach ($mb in $(Get-Mailbox -ResultSize Unlimited)) {
    if ($msol_year_members_table.ContainsKey($($mb.ExternalDirectoryObjectId))) {
        $msol_year_members_table[$($mb.ExternalDirectoryObjectId)]
    }
}

这样做虽然有效:

foreach ($mb in $(Get-Mailbox -ResultSize Unlimited)) {
    if ($result = $msol_year_members_table.GetEnumerator() | ?{ $_.Name -eq $($mb.ExternalDirectoryObjectId) }) {
        $result
    }
}

任何指针都会受到赞赏 - 假设这是一个愚蠢的错误。

2 个答案:

答案 0 :(得分:2)

您确定键和测试值之间没有类型不匹配吗? 当您使用.containskey()方法时,参数值必须与键的类型相同,但是当您使用.getenumerator()方法时,-eq测试将尝试强制执行。名称值和测试值为操作的相同类型:

$ht = @{
1 = 'one'
2 = 'two'
3 = 'three'
}

$ht['1']

$ht.GetEnumerator() |? { $_.name -eq '1'}

Name                           Value                                                                      
----                           -----                                                                      
1                              one                                                                        

答案 1 :(得分:0)

以下是我的工作代码 - 以防万一它可以帮助任何人,我用它来为dir同步组分配地址簿政策到Office 365邮箱:

# Years to be processed
$years = @("2015","2016","2017","2018","2019","2020","2021","2022","2023","2024","2025","2026","2027")

# Loop through each year and retrieve the members for the groups
$msol_year_members_table = @{}
foreach ($year in $years) {
    foreach ($member in $(Get-MsolGroupMember -GroupObjectId $(Get-MsolGroup | ?{ $_.DisplayName -eq $("Class of " + $year) }).ObjectId)) {
        $key = $member.ObjectId.ToString()
        $msol_year_members_table[$key] = $member
    }
}

# Loop through the mailboxes and set the mailbox poilicies for matching members
foreach ($mb in $(Get-Mailbox -ResultSize Unlimited)) {
    $key = $mb.ExternalDirectoryObjectId.ToString()
    if ($msol_year_members_table.ContainsKey($key)) {
        $alias = $msol_year_members_table[$key].Alias; $alias_split = $alias.Split(".")
        $year = $alias_split[$alias_split.Length-1)]
        Set-Mailbox -Identity $alias -AddressBookPolicy $("Class of " + $year + " ABP")
    }
}