开发者

powershell hashtable.containsValue returns false, but looping the values gets a match?

So I'm trying to create a function in powershell that nests all the groups a user is member of in ad. I map the groups into a hashtable, with the common name from AD as the value.

This goes well, and the function returns a hashtable containing all my groups. but when I query it using $group = "IT-Avd" $groups.ContainsValue($group)

It returns false -- but when I loop over the values and do the same comparison, I do get a match! what's going on??

function get-groupmemberships ($workDN){
    $ADobj = [ADSI]"LDAP://$workDN"     
    foreach ($currGroup in $ADobj.memberOf.Value){
        if (!($currGroup -eq $null)){
            #Write-Host "displayN:" $grpDetails.Name " | dn:" $currGroup " | "
            if(!$groups.ContainsKey($currGroup)){
                $grpDetails = [ADSI]"LDAP://$currGroup"
                $groups.Add($currGroup,$grpDetails.Name)
                #Write-Host "Adding new pair, " $grpDetails.Name " | " $currGroup
                get-groupmembership $currGroup
            }
        }
    }
    return $groups
}

function get-DN ($SAMToFetch){
    $strFilter = "(samAccountName=$SAMToFetch)"
    $objSearcher = New-Object System.DirectoryServices.DirectorySearcher
    $objSearcher.Filter = $strFilter
    $objPath = $objSearcher.FindOne()
    if($objPath){
        $objFound = $objPath.GetDirectoryEntry()
        $objDN = $objFound.distinguishedName
        return $objDN}
    else{ 
        return $false
    }
}

$groups = @{}   
write-host "Start search:",(Get-Date -Format T),",",(get-Date -format fff)
$group = "IT-Avd"
$memberOf = get-GroupMemberships (get-DN jslonsetteig)
$groups.ContainsValue($group)
forea开发者_运维知识库ch( $val in $groups.Values){if ($val -eq $group){Write-Host $val "<--It does seem to be there..."}}

write-host "End search:",(Get-Date -Format T),",",(get-Date -format fff)`


Using ContainsValue is using a linear search of the hashtable so you're losing the benefit of the O(1) search the hashtable normally offers. You might try creating another hashtable where the common name is the key instead. Then you would use ContainsKey or just attempt the access by name and see if the result is not $null.

BTW one reason for the difference is that when you pass $group to ContainsValue, PowerShell does nothing in the way of type coercion since that method parameter is type object. However when it executes $val -eq $group, PowerShell will potentially do lots of work to coerce $group to $val's type. Now while it may appear that $group is a string already, there are some psobject wrapping bugs that may be coming into play here (just a guess though). What happens if you try $groups.ContainsValue('IT-Avd')?

You might also examine the type stored in the hashtable e.g.:

$groups.Values | Get-Member
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜