0

I need a PowerShell script to count the members of an AD group that have the extensionAttribute4 property equal to o365_facstaff.

I’ve been using the following script to count all members of the group but I specifically need just the ones with the property:

$ADInfo = Get-AdGroup -Identity ‘<group name>’ -Properties Members 
$ADInfo.Members.Count
  • 1
    `$ADInfo.Members |Where-Object {(Get-ADUser $_ -Properties extensionAttribute4).extensionAttribute4 -eq 'o365_facstaff'} |Measure-Object` – Mathias R. Jessen Sep 09 '21 at 15:34

1 Answers1

0

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.

codewario
  • 19,553
  • 20
  • 90
  • 159