title: Export CSV of AD SamAccountNames and Groups for every user in specific OU
body: <p>I found a similar question <a href="https://stackoverflow.com/questions/30329665/powershell-ad-return-users-from-within-any-groups-in-a-specific-ou-plus-coun">here</a>, but it doesn't quite fit my need and I am having trouble tweaking it to do so.</p>
  
  <p>I need to create a <code>.csv</code> file of all users in a specific OU along with what their AD group membership is in the following format:</p>
  
  <pre class="lang-none prettyprint-override"><code>User, Group (This is a Header)
  User1, Group1
  User1, Group2
  User1, Group3
  User2, Group1
  User3, Group1
  User4, Group1
  User4, Group2
  </code></pre>
  
  <p>I think this script gets me most of the way there:</p>
  
  <pre><code>$Users = Get-ADGroup -SearchBase "OU=OrgUnit1,OU=OrgUnit2,OU=OrgUnit3,DC=XXX,DC=LOCAL" -Filter * `
      | Get-ADGroupMember -Recursive `
      | ForEach-Object { Get-ADUser $_ –Properties MemberOf | Select SamAccountName, MemberOf; } `
      | Sort-Object SamAccountName
      | export-csv C:\Messaging\PowerShell\ADUsers\Test1.csv
  </code></pre>
  
  <p>The problem with this is two fold. </p>
  
  <ol>
  <li><p>I want to search on <code>OU=OrgUnit1</code> without having to search on the full distinguished name, because the sub OU's aren't always the same.</p></li>
  <li><p>The <code>.csv</code> output has the full distinguished name of the AD Group and I need just the Name of the group with no qualifiers</p></li>
  </ol>