Reputation: 13
I have been trying the following PowerShell script in several AD domain, but in one 2008 R2 domain it fails and I cannot find the reason for it:
PS D:\> Add-type -AssemblyName System.DirectoryServices.AccountManagement
PS D:\> $ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
PS D:\> $Domain = $env:USERDOMAIN
PS D:\> $pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct,$Domain
PS D:\> $user = System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($pc, "SamAccountName", "testuser")
PS D:\> $groups = $user.GetAuthorizationGroups()
D:\> $groups
Normally the script gives a list of groups but for this domain it gives the following error message (after the list of groups):
An error occurred while enumerating through a collection: The specified directory service attribute or value does not exist.
CategoryInfo:InvalidOperation(System.Director...ment.Principal]:FindResultEnumerator`1) [], Runtime
Exception
FullyQualifiedErrorId : BadEnumeration
Could this have anything to do with AD privileges or permission?
Upvotes: 1
Views: 6229
Reputation: 13523
I this could happen for a few possible reasons:
Some possible solutions:
$ErrorActionPreference = "SilentlyContinue"
(Very rough code as a starting point)
$searchRoot = New-Object System.DirectoryServices.DirectoryEntry
$adSearcher = New-Object System.DirectoryServices.DirectorySearcher
$adSearcher.SearchRoot = $searchRoot
$adSearcher.Filter = "(samAccountName=UserName)"
$adSearcher.PropertiesToLoad.Add("memberOf")
$samResult = $adSearcher.FindOne()
if($samResult)
{
$adAccount = $samResult.GetDirectoryEntry()
$groupMembership = $adAccount.Properties["memberOf"]
$groupMembership | foreach {
Write-Host $_
}
}
Upvotes: 1