Home > Blockchain >  get-adgroupmember inconsistently returns group members
get-adgroupmember inconsistently returns group members

Time:10-25

I've been writing powershell since powershell 2, and I've run into something odd I've never seen before.

$groups = get-adgroup -filter {name -like 'SomeGroup*'} | select name | sort name

foreach ($group in $groups){
    $groupsid = $group.name
    write-host $groupsid
    Get-ADGroupMember $groupsid | select name | sort name
    write-host "`n`n"
}

The get-adgroupmember in the foreach loop is only enumerating members in certain groups and not in others.

If "$groupsid" = "DeveloperGroup" and I use get-adgroupmember DeveloperGroup | select name | sort name in the shell, then I get back what I expected to see: a list of group members. But for several groups that are enumerated by the first line, I get nothing back when the exact same cmdlet is executed within the foreach loop. I know some of the cmdlets are still a little buggy, just no idea why this is being intermittent in what the loop decides to fetch.

CodePudding user response:

I have edited few lines of your cmdlet and it is working fine for me. Please use the below formatted PowerShell command to get your desire output.

$groups = get-adgroup -filter {name -like 'Group*'} | sort name
$results = foreach ($group in $groups) {
    Get-ADGroupMember $group | select samaccountname, name, @{n='GroupName';e={$group}}, @{n='Description';e={(Get-ADGroup $group -Properties description).description}} | sort name
}
$results
$results | Export-csv C:\GroupMemberShip.txt -NoTypeInformation

enter image description here

enter image description here

CodePudding user response:

@Doug Maurer comment is helpful and may be part of the issue.

Another problem: avoid using the name of the group. Either use the group object directly as input of the Get-ADGroupMember cmdlet like below, or use the DistinguishedName property of the group.

foreach ($group in $groups){
    Get-ADGroupMember $group | select name | sort name
    write-host "`n`n"
}
  • Related