title: Powershell - How to remove trailing spaces from a list of groups a user is in
body: <p>I've copied/created a script to get all the members of a group that a user is part of, including nested groups. However, my output isn't quite the way I want it.</p>
  <p>It goes in one of two ways. Either it outputs as one big string, which looks nice, but has trailing spaces on each line so I cannot simply copy and paste it into AD. Or if I change the Out-String to use -stream, it comes out as a garbled mess, but may allow me to trim the spaces.</p>
  <p>I currently have the output going into a TextBox in a simple GUI.</p>
  <pre><code>Function Get-ADUserNestedGroups {
  Param
  (
      [string]$DistinguishedName,
      [array]$Groups = @()
  )
  
  #Get the AD object, and get group membership.
  $ADObject = Get-ADObject -Filter &quot;DistinguishedName -eq '$DistinguishedName'&quot; -Properties memberOf, DistinguishedName;
  
  #If object exists.
  If($ADObject)
  {
      #Enummurate through each of the groups.
      Foreach($GroupDistinguishedName in $ADObject.memberOf)
      {
          #Get member of groups from the enummerated group.
          $CurrentGroup = Get-ADObject -Filter &quot;DistinguishedName -eq '$GroupDistinguishedName'&quot; -Properties memberOf, DistinguishedName;
     
          #Check if the group is already in the array.
          If(($Groups | Where-Object {$_.DistinguishedName -eq $GroupDistinguishedName}).Count -eq 0)
          {
              #Add group to array.
              $Groups +=  $CurrentGroup;
  
              #Get recursive groups.      
              $Groups = Get-ADUserNestedGroups -DistinguishedName $GroupDistinguishedName -Groups $Groups;
          }
      }
  }
  
  #Return groups.
  Return $Groups;
  }
  
   Function Display-UserGroups {
  
  #Get all groups.
  $Groups = Get-ADUserNestedGroups -DistinguishedName (Get-ADUser -Identity $userSAM).DistinguishedName;
  
  $ResultsTextBox.Text = $Groups | Select-Object Name| Sort-Object name | Out-String
  </code></pre>
  <p>The output with the first way looks like:</p>
  <p>Group Name1(Eight Spaces Here)</p>
  <p>Group Name2(Eight Spaces Here)</p>
  <p>The output with the second way looks like:</p>
  <p>Group Name1GroupName2GroupName3</p>
  <p>Thanks for your help!</p>