I was recently asked to provide the username and email address of our Active Directory users in a specific group. This seemed an easy task on the surface. I ran this code on a small group and worked flawlessly.
Get-ADGroupMember -identity ‘groupname’ | get-aduser -Properties mail |select samaccountname,mail
So I ran the same code on the large group, but it didn’t work. I got this timeout error instead:
Get-ADGroupMember : The operation returned because the timeout limit was exceeded.
At line:1 char:1
+ Get-ADGroupMember -identity ‘groupname’
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationTimeout: (groupname:ADGroup) [Get-ADGroupMember], TimeoutException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.TimeoutException,Microsoft.ActiveDirectory.Management.Commands.G
etADGroupMember
I did some research and found that Get-AdGroupMember does not always work well on large groups. It waits for a bit and then times out rather than return results.
I found a workaround that works well and does not give timeouts. Below is a screenshot of the working code, along with the text so you can copy/paste it in. Just change “YourGroupName” to the name of your group. If you need any additional properties, add them to my Get-ADUser line.
Screenshot of Working Code:
Working Code:
$searchRoot = New-Object System.DirectoryServices.DirectoryEntry
$adSearcher = New-Object System.DirectoryServices.DirectorySearcher
$adSearcher.SearchRoot = $searchRoot
$adSearcher.Filter = “(cn=YourGroupName)”
$adSearcher.PropertiesToLoad.Add(“member”)
$samResult = $adSearcher.FindOne()
if($samResult)
{
$adAccount = $samResult.GetDirectoryEntry()
$groupMembership = $adAccount.Properties[“member”]
#$groupMembership | foreach { Write-Host $_ }
}
foreach ($member in $groupmembership) {
Get-ADUser -Filter {distinguishedname -eq $member} -Properties mail | Select-Object samAccountName, mail
}