Home > Enterprise >  Powershell : getting memberships and the number of members of the group
Powershell : getting memberships and the number of members of the group

Time:05-19

If the number of members of the group is less than 3 I want to export those members like below. by the way , there are nested groups too.

My desired output:

Members,Group Name,Members Count,Members
NO,Group01,10
NO,Group02,1,user01
YES,Group03,2,user01;user02

Here is my script :

Import-Csv -Path "C:\tmp\unused.csv" | ForEach-Object {
    $out = @{ 'Group Name' = $_.Name }
    if((Get-ADGroup $_.Name -Properties Member).Member) {
        $out['Members'] = 'YES'
    }
    else {
        $out['Members'] = 'NO'
    }
    [pscustomobject] $out
} | Export-Csv "C:\tmp\export.csv" -NoTypeInformation -Encoding UTF8

CodePudding user response:

This should give you the expected result, note that Get-ADGroupMember will return all members recursively for each group, if this is not what you want, remove the -Recursive parameter.

Also note, this may return any object class as member of the group (computers, other groups, users, service accounts...), you want to only target Users as members, use the following:

$members = @(Get-ADGroupMember $_.Name -Recursive).where{ $_.objectClass -eq 'user' }

Code

Import-Csv -Path "C:\tmp\unused.csv" | ForEach-Object {
    $out = [ordered]@{
        'HasMembers'    = ''
        'Group Name'    = $_.Name
        'Members Count' = ''
        'Members'       = ''
    }
    # using `-Recursive` since there can be nested groups
    $members = @(Get-ADGroupMember $_.Name -Recursive)
    # if count is 0
    if(-not $members.Count) {
        $out['HasMembers'] = 'NO'
    }
    # if count is lower than 3 and greater than 0
    elseif($members.Count -lt 3) {
        $out['HasMembers'] = 'YES'
        $out['Members'] = $members.Name -join ';'
    }
    # if count is greater than 2
    else {
        $out['HasMembers'] = 'YES'
    }
    $out['Members Count'] = $members.Count
    [pscustomobject] $out
} | Export-Csv "C:\tmp\export.csv" -NoTypeInformation -Encoding UTF8
  • Related