freeWind
freeWind

Reputation: 148

How to check a list of groups to see if there are members

I've been working on a script to run through a list of groups in a CSV file to see if they have any members. Ultimately I'm looking to have the script export the results to a separate CSV file.

$groups = Get-Content 'C:\Users\me\Desktop\testGroups.csv'

foreach ($groups in $groups) {
    $users = Get-ADGroupMember -Identity $groups 
    if (($users | Measure-Object).Count -ne 0) {Write-Output "$groups has something" | Out-File C:\Users\me\Desktop\membersTest.csv -Append}
    Else {Write-Output "$groups has nothing" | Out-File C:\Users\me\Desktop\membersTest.csv -Append} 
} 

This returns the following:

Length
27
31
41
30
...

I've attempted to change Write-Output to Write-Host and that appears to return the correct results, but it only displays it within the CMD window obviously.

Would someone be able to assist me with the process of correcting these IF Else statements?

Upvotes: 0

Views: 543

Answers (2)

user6811411
user6811411

Reputation:

End result is a csv, so build an object and export it.

$groups = Get-Content 'C:\Users\me\Desktop\testGroups.csv'

$GroupMemberCount = ForEach ($group in $groups) {
    [PSCustomObhect]@{
       Group = $group
       MemberCount = (Get-ADGroupMember -Identity $group).Count
    }
}
$GroupMemberCount | Out-Gridview
$GroupMemberCount | Export-Csv 'C:\Users\c002568\Desktop\membersTest.csv' -NoTypeInformation

Upvotes: 1

Ketanbhut
Ketanbhut

Reputation: 506

I had this similar script for another project which might be helpful, I've modified to match your query. If you don't have need to display output, you can ignore that.

$groups = import-csv groups.csv
$outputFile = New-Item -ItemType file testOutputCSV.CSV -Force

foreach ($group in $groups) {
    [array]$users = Get-ADGroupMember -Identity $group.samaccountname
    if($users.count -ne 0){
        Write-Output "$($group.samaccountname) has something " 
    }
    else {
        Write-Output "$($group.samaccountname) has 0 members" 
    }
    $group.samaccountname +","+$users.count | Out-File $outputFile -Append
}

If the intention is to highlight the groups not having any members on console, as well as CSV, you can bring this line inside IF Else block, add more columns as needed.

$group.samaccountname +","+$users.count | Out-File $outputFile -Append

If you don't need to display anything on the console, you can omit IF Else block.

If you want to update CSV only for groups having 0 members or non-zero members, you can modify accordingly.

Edit: Masked $Users to be [array] since single member groups would return ADPrincipal

Upvotes: 1

Related Questions