Jakodns Jakodns - 10 months ago 47
PowerShell Question

How to count the result of a if loop within foreach loop

Is there a better way to be able to count the amounts of empty groups than using this method and then calling $count + 1 for each result? I tried to mess around with

but it kept returning 0

$Groups = Get-ADGroup -Properties * -Filter * | where { $_.Members.Count -eq 0}
$123= Foreach($G In $Groups)
$Membership = Get-ADGroupMember -Identity $G.Name
If($Membership.count -eq 0){
$Count = $count + 1



Get-ADGroup can do much of what you ask without going away from AD.

Getting this done with the Filter parameter is painful. The LDAP filter however is simple.

For empty groups:

Get-ADGroup -LdapFilter "(!member=*)"

For empty groups which are also not nested inside other groups:

Get-ADGroup -LdapFilter "(&(!memberOf=*)(!member=*))"