title: powershell retrieve members of group recursively
body: <p>I got a pretty big audit project that I'm hoping to automate.</p>
  
  <p>I need to get every user's name, SamAccountName, Title and Department who are part of a group. Problem is, the group has groups within it and those groups have groups within them. Another problem is that about 99% of all the groups have an asterisk in it's Display Name (NOT SamAccountName).</p>
  
  <p>Here is the code I currently have, it works fine until it receives a group with an asterisk in it's name.. (hence the .Replace("*","") part.... Anyone got any ideas on how to fix this?</p>
  
  <pre><code>function Get-NestedGroupMember {
  [CmdletBinding()] 
  param(
      [Parameter(Mandatory)] 
      [string]$Group 
  )
  $broke = @();
  ## Find all members  in the group specified 
  $members = Get-ADGroupMember -Identity $Group 
  foreach ($member in $members){
      ## If any member in  that group is another group just call this function again 
      if ($member.objectClass -eq 'group'){
          $memberGroup = $($member.Name).Replace("*", "")
          try{
              Get-NestedGroupMember -Group "$($memberGroup)"
          }catch{
              $broke += "$($memberGroup)`n"
          }
      }else{
          ## otherwise, just  output the non-group object (probably a user account)
          $member.Name  
      }
  }
  Write-Host "`nThe following groups could not be found automatically.`n`n$($broke)"
  }
  
  $getGroup = Read-Host -Prompt "Group name"
  
  Get-NestedGroupMember $getGroup
  </code></pre>