title: Get recursive group membership of all AD users using Powershell
body: <p>I'm trying to make a PS script which would list all Active Directory user group membership (recursive).</p>
  
  <p>I already have working script:</p>
  
  <pre><code>import-module activedirectory
  
  $users = get-aduser -Filter {Name -Like "*"} -Searchbase "ou=Users, dc=Domain" | Where-Object { $_.Enabled -eq 'True' } 
  
  $targetFile = "D:\users.csv"
  rm $targetFile
  Add-Content $targetFile "User;Group"
  
  
  foreach ($user in $users)
  {
      $groups = Get-ADPrincipalGroupMembership $user
  
      foreach ($group in $groups)
      {
          $username = $user.samaccountname
          $groupname = $group.name
          $line = "$username;$groupname"
          Add-Content $targetFile $line
      }
  }
  </code></pre>
  
  <p>But script doesn't list groups recursively, i.e., if group listed in the output file is part of another group.</p>
  
  <p>Example:</p>
  
  <p>Group1: User</p>
  
  <p>Group2: Group3: User</p>
  
  <p>Script shows only Group1 and 3 but not 2.</p>
  
  <p>What should I add to the first script that it writes group membership recursively?</p>