locked
I know I have done this before, but I am hitting a memory lapse or something on how to count objects in a foreach loop RRS feed

  • Question

  • I am trying to count the number of systems that are members of two AD groups, but I cannot seem to get it. 

    Here is what I have:

     $Group1 = 'ADGroup1'
    
    $Group2 = 'ADGroup2'
    
    $Group1Members = Get-ADGroupMember -Identity $Group1
    
    $Group2Members = Get-ADGroupMember -Identity $Group2
    
    Foreach ($Group1Member in $Group1Members)
    {
        Foreach ($Group2Member in $Group2Members)
        {
            If ($Group1Member.name -match $Group2Member.name)
            {
               # Display total count here of systems that are members of both AD groups (how do I do this?)
            }
        }
    } 

    Thanks for any help on this. 


    Thursday, December 21, 2017 8:03 PM

Answers

  • (Compare-Object$Group1Members $Group2Members -Property Name -IncludeEqual|?{$_.SideIndicator -eq '=='}).Count

    \_(ツ)_/

    Thursday, December 21, 2017 8:29 PM

All replies

  • You don't need loops.

    $Group1Members = Get-ADGroupMember -Identity $Group1
    $Group2Members = Get-ADGroupMember -Identity $Group2
    Compare-Object $Group1Members $Group2Members -Property Name 


    \_(ツ)_/

    Thursday, December 21, 2017 8:12 PM
  • I need a count. 
    Thursday, December 21, 2017 8:18 PM
  • Wait, I can use the -IncludeEqual param and just count those, right?
    Thursday, December 21, 2017 8:27 PM
  • (Compare-Object$Group1Members $Group2Members -Property Name -IncludeEqual|?{$_.SideIndicator -eq '=='}).Count

    \_(ツ)_/

    Thursday, December 21, 2017 8:29 PM
  • Okay, that worked. I just did the following to give me the count I needed. 

     $Group1 = 'ADGroup1'
    $Group2 = '_ADGroup2'
    $Group1Members = Get-ADGroupMember -Identity $Group1
    $Group2Members = Get-ADGroupMember -Identity $Group2
    (Compare-Object $Group1Members $Group2Members -Property Name -IncludeEqual | 
            Where-Object -FilterScript {$_.SideIndicator -eq '=='} |
                Measure-Object).Count 

    Thanks jrv, appreciate it. 


    Thursday, December 21, 2017 8:31 PM
  • But, I am just curious how I would count in the foreach loop?
    Thursday, December 21, 2017 8:32 PM
  • By re-writing the code to do what compare-object does.

    No rational programmer would use loops that way to compare lists.  We would use dictionaries or some form of grouping such as group-object based on  a dictionary.


    \_(ツ)_/


    • Edited by jrv Thursday, December 21, 2017 8:41 PM
    Thursday, December 21, 2017 8:40 PM
  • Yes!

    I am an irrational programmer, I suppose.

    In all honestly, I completely forgot about Compare-Object. 

    Thanks again for the help, appreciate it. 


    Friday, December 22, 2017 3:31 AM