Author Posts

August 10, 2018 at 12:48 pm

Hello!

I have the code below:



$ADPath = 'OU=Groups,DC=contoso,DC=com';

$GroupsList = Get-ADGroup -SearchBase $ADPath -Filter *

For ($i=0; $i -lt $GroupsList.Length; $i++) {

Clear-Variable Count;

$Count = (Get-ADGroupMember -Identity $GroupsList[$i] -Recursive).Count

$GroupsList[$i].Name+','+$Count

}

It finds the groups within ActiveDirectory, reads those and counts its members.

I would like to export those information to CSV file. But I don't know how. Using array or may be some custom variables.

I can simply copy those info from ISE and paste it where I want, but it's not a good variant.

 

Another problem with this code: if a group has only one member method Count resolves me no information (not null, nothing).

If a group has no members method Count resolves me 0 (zero), that is works correctly.

Thank for your help!

 

August 10, 2018 at 1:16 pm

As a "quick & dirty" start you could use something like this:

$ADPath = 'OU=Groups,DC=contoso,DC=com'
$GroupList = Get-ADGroup -SearchBase $ADPath -Filter * |
    ForEach-Object {
        $GroupMemberList = Get-ADGroupMember -Identity $_.DistinguishedName -Recursive -ErrorAction SilentlyContinue
        [PSCustomObject]@{
            ADGroup = $_.Name
            MemberCount = $GroupMemberList.Count
        }
    }
$GroupsList | Format-Table -AutoSize
$GroupsList | Export-Csv -Path 'GroupList.csv' -Delimiter ',' -NoTypeInformation -Encoding UTF8

August 10, 2018 at 2:18 pm

Another problem with this code: if a group has only one member method Count resolves me no information (not null, nothing).

This is a Powershell gotcha, which you can read about in the in the free ebook The Big Book of PowerShell Gotchas in the above link. Basically, if there is a single object, Powershell is doing a conversion that breaks the Count property. The fix is simple, and I try to do it in all of my code even though it's supposed to be fixed. For instance, the variable is $GroupMemberList, so if you wrap it in an array like so because the Count is returning from an array object:

@($GroupMemberList).Count

There are also a lot of pre-built report you can try as well that will give a ton of information:

https://gallery.technet.microsoft.com/office/Active-Directory-Audit-7754a877

Active Directory reporting

August 11, 2018 at 11:30 am

Thank you very much!