How to count a users group membership in powershell
In our sample code today we demonstrate how to easily count a user objects group membership. An example scenario is when investigating user kerberos token bloat. Token bloat can occur when a users group membership causes the kerberos token to “bloat” above the accepted level – you can read more about it here. When this happens, it can be important to identify users with large group membership – these users can then be targeted for group rationalisation/reduction.
An important note, the below only returns and counts the top level groups, aka, nested groups are not considered. If your AD structure contains many nested groups you may need to consider some changes to capture nested group membership (this causes most of the token bloat).
# Either create an array of target users or import via a file $colUser = "user1","user2" # Create a report array object $UserReport = @() foreach ($objUser in $colUser) { # Cycle through our target users $ErrorFlag = $false Try { # Attempt to enumerate and count the target users group membership $count = Get-ADPrincipalGroupMembership $objUser | measure | select -expand count } Catch { # If we get an error - capture it and skip adding this user to the report write-host "Error: $_" $ErrorFlag = $true } If (!$ErrorFlag) { # When we don't have an error - add the user details to a hash object $UserHash = @{ Username = $objUser Groupcount = $count } # Create a new object using our hash object $objUserInfo = New-Object PSObject -Property $UserHash # Add the new object to the reporting array $UserReport += $objUserInfo } } # Output our report object sorted by descending group membership numbers $UserReport | sort -desc Groupcount
There it is – an easy way to count a users group membership.