To find the number of occurrences of items in an array, the group object is fantastic.
Say you have a variable containing an array with a big list of names which are in the array multiple times. This command returns how many times each name occurs in the array. Easy or what?
#Create the Array Variable
$ArrayVariable = New-Object System.Collections.Generic.List[System.Object]
#Define a bunch of groups
$GroupsList = get-adgroup -filter {name -like "GROUP-G-*Bentley*" -or name -like "GROUP-G-*Microstation*"} | select -expand name | sort name
#Put all the users in all the group into an array
foreach ($Group in $GroupsList)
{
$GroupUsers = Get-ADGroupMember $Group | where {$_.objectclass -eq "user"} | select -expand samaccountname
foreach ($GroupUser in $GroupUsers)
{
$AllFoundUsersArray.Add($GroupUser)
echo $GroupUser
}
}
#Display the number of groups each user is in.
$ArrayVariable | group | sort count -Descending | select name,count
Output:
Name Count
---- ----
John 5
Alice 4
Bob 3
Tim 2
Baltar 1
Now check out this neat trick. Reverse the array order :)
[array]::Reverse($ArrayVariable)