title: Powershell Adding users within groups to cross forest groups
body: <p>This script works without error now, but the problem is that when several groups in the searchbase are found, the script will add all users from all groups to the cross forest target groups.</p>
  
  <p>So for example:</p>
  
  <p>ForestAGroup1 = contains 2 users</p>
  
  <p>ForestAGroup2 = contains 2 users</p>
  
  <p>::runs script::</p>
  
  <p>now...</p>
  
  <p>ForestBGroup1 = contains 4 users</p>
  
  <p>ForestBGroup2 = contains 4 users</p>
  
  <p>The ForestBGroup1/2 needs to contain the same identical users as ForestAGroup1/2.</p>
  
  <p>Here is the script for reference:</p>
  
  <pre><code>    $creds = Get-Credential
  $Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domainA,DC=com" | export-csv c:\temp\test.csv
  $Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=TEST,OU=Shop Print Groups,OU=User,OU=domain Groups,DC=domainA,DC=com"
  Foreach($G In $Groups)
  {
      #Display group members and group name
      Write-Host $G.Name
      Write-Host "-------------"
      $G.Members
  
      #Add members to domainB group
      $domainGMembers = import-csv C:\temp\test.csv | ForEach-Object -Process {Get-ADGroupMember -Identity $_.CN} | Select-Object samaccountname | export-csv c:\temp\gmembers.csv
  
      $domainDNUser = import-csv C:\temp\gmembers.csv | ForEach-Object -Process {Get-ADUser $_.samaccountname -Server "domainA.com" -properties:Distinguishedname}
  
      import-csv C:\temp\gmembers.csv | ForEach-Object -Process {Add-ADGroupMember -Server "domainB.com" -Identity $G.Name -Members $domainDNUser -Credential $creds -Verbose}
  
  }
  </code></pre>