We can get this information from AD with a single -Filter
query on Get-ADUser
:
# We'll need the group DN instead of the group name
# Here's an example
$groupDn = 'CN=test_group,CN=Users,DC=bender,DC=net'
# Get all ADUsers member of the target group with the specific
$groupMembers = Get-ADUser -Filter "(memberOf -RecursiveMatch '$groupDn') -and (extensionAttribute4 -eq 'o365_facstaff')"
# Check the Count property like you would with any array
$groupMembers.Count
Alternatively, as also mentioned in the comments, you can get the group members off of the ADGroup
and further filter, though this results in additional unnecessary local processing. This can become problematic with very large groups, especially if your ADDS infrastructure runs closer to the minimum system requirements:
# Using $ADInfo from your code sample
$membersWithfacstaff = $ADInfo.Members | Where-Object {
( Get-ADUser $_ -Properties extensionAttribute4 ).extensionAttribute4 -eq 'o365_facstaff'
}
# Use the Count property
$facstaff.Count
As also mentioned in the comments, Measure-Command
will give you the count too but is a bit redundant here, considering you'd have to reference the Count
property anyways if you want to use it programmatically.
See this answer of mine for more information on effectively using the -Filter
parameter on the RSAT AD cmdlets.