2

Maybe a dumb question, but I can't really understand why this is happening.

Simple PS script - to count AD user groups. But for users who is member of the primary group only, the counter is empty. When I query the same user with a command manually - the counter works.

If a user is a member of any other group, then the script works fine.

As an example:

...
foreach ($user in $users)
    {
        $SAM = $user.SamAccountName
        $groups = Get-ADPrincipalGroupMembership -Identity $SAM | select name
        $SAM
        $groups.count
...

Output

SomeUser
2
SomeUser1
SomeUser2
SomeUser3
37
...

If I query SomeUser1 manually

(Get-ADPrincipalGroupMembership -Identity SomeUser1 | select name).count
1
  • 3
    Wrap it in an array `@(Get-ADPrincipalGroupMembership -Identity $SAM)` then you ensure there is always a `.Count` property ;) – Santiago Squarzon Jan 27 '23 at 00:52
  • 1
    That helped. Thank you. I knew that I'm missing something small. – Sergei Galaktionov Jan 27 '23 at 00:57
  • What you're seeing is a _bug_ in _Windows PowerShell_, which has since been fixed in PowerShell (Core) 7+ : PowerShell is designed to report an intrinsic `.Count` property for _any_ scalar object that doesn't have a type-native property of that name, with value `1`, for unified handling of collections and scalars. In Windows PowerShell, this unexpectedly doesn't work for `[pscustomobject]` instances, such as returned by `Select-Object`. The workaround is to use `@(...).Count` - so as ensure that the value of interest is treated as an _array_ (which has a type-native `.Count` property). – mklement0 Jan 27 '23 at 03:12

0 Answers0