Help with export to CSV

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!

 

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

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
http://kpytko.pl/active-directory-domain-services/active-directory-reporting/

Thank you very much!