0

I am trying to extract the group membership count from each of the server I supply. Below script works for that:

$computers = gc D:\Samir-PS\serverlist.txt
$computers | foreach {
    $computername = $_
    [ADSI]$S = "WinNT://$($env:computername)"
    $S.children.where({$_.class -eq 'group'}) |
        Select @{Name="Name";Expression={$_.name.value}},
            @{Name="Members";Expression={
                [ADSI]$group = "$($_.Parent)/$($_.Name),group"
                $members = $Group.psbase.Invoke("Members")
                ($members | ForEach-Object {
                    $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
                }) -join ";"
            }}
} | Export-Csv -Path d:\samir-ps\audit.csv

but, I want to refine the output while it is generated. If the group does not have any members in it, it should not write to the CSV file. So it should only write groups which got one or more members in it. The solution should also improve the performance. Please suggest all the possible ways to do this if there are more than one.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Samir Jain
  • 41
  • 1
  • 1
  • 9

1 Answers1

1

You can use .count to validate and loop around that. Try this in your code: if(($members.count) -gt 0)

below:

$computers = gc D:\Samir-PS\serverlist.txt
$computers | foreach {
    $computername = $_
    [ADSI]$S = "WinNT://$($env:computername)"
    $S.children.where({$_.class -eq 'group'}) |
        Select @{Name="Name";Expression={$_.name.value}},
            @{Name="Members";Expression={
                [ADSI]$group = "$($_.Parent)/$($_.Name),group"
                $members = $Group.psbase.Invoke("Members")
                if(($members.count) -gt 0)
                {
                ($members | ForEach-Object {
                    $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
                }) -join ";"
                }
            }}
} | Export-Csv -Path d:\samir-ps\audit.csv