title: Efficient iteration through AD Group Membership
body: <p>I'm just going to five straight in with what I have, the scenario is a little too complex to explain off the mark.</p>
  
  <p><strong>XML config:</strong> </p>
  
  <pre><code>  &lt;Groups&gt;
      &lt;Group priority="1" name="testGroup1" profile="testProfile1"/&gt;
      &lt;Group priority="2" name="testGroup2" profile="testProfile2"/&gt;
      &lt;Group priority="3" name="testGroup3" profile="testProfile3"/&gt;
      &lt;Group priority="4" name="testGroup4" profile="testProfile4"/&gt;
    &lt;/Groups&gt;
  </code></pre>
  
  <p><strong>Powershell:</strong></p>
  
  <pre><code>$userProfileHash = [ordered]@{}
  # Itterate through groups
  foreach ($group in ($homeNode.ApplicationMethod | ? {$_.id -eq "adgroup"}).Groups.Group | Sort-Object $_.priority) {
    # Get group members, Itterate through them
    Get-ADGroupMember -Identity $group.name | ForEach-Object {
      # Add to ordered hash
      try {
        $userProfileHash.Add($($_.samaccountname),$group.profile)
      } catch {#don't want to see errors, there may be many}
    }
  }
  </code></pre>
  
  <p><strong>Now I'll to to explain:</strong></p>
  
  <p>To protect against a user being a member of more than 1 of the defined groups. I sort the groups by priority (in the foreach expression) and then use the hashtable rule that the key must be unique. </p>
  
  <p>This ensures that each user is only added once and that they will be assigned the profile of the group they appeared in first.</p>
  
  <p>I don't really like this approach, but it was the quickest of the approaches I tried: 5 Seconds with 1100 test users.</p>
  
  <p><strong>Question:</strong> </p>
  
  <p>How can I speed up this code? 
  (there may be tens of thousands of users when this is in production)</p>