title: Get UPN from Get-ADGroupMember
body: <p>I have a task to get <strong>userPrincipalName</strong> attribute from users who are in several groups in our multiple-domain AD forest.</p>
  
  <p>The problem is that I can't use Select-Object to get a user's UPN from Get-ADGroupMember because this cmdlet only returns a limited number of properties (samaccountname, name, SID and DN), and UPN isn't one of them.</p>
  
  <p>I wrote this code (get "name" and than search UPN by "name"):</p>
  
  <pre><code>    $ScriptPath = Split-Path $MyInvocation.MyCommand.Path
      $LocalSite = (Get-ADDomainController -Discover).Site
      $NewTargetGC = Get-ADDomainController -Discover -Service 6 -SiteName 
      $LocalSite
      IF (!$NewTargetGC)
      { $NewTargetGC = Get-ADDomainController -Discover -Service 6 -NextClosestSite }
      $NewTargetGCHostName = $NewTargetGC.HostName
      $LocalGC = “$NewTargetGCHostName” + “:3268”
  
      $domains = (Get-ADForest).domains
      $MembersOfSFDC_Groups = foreach ($domain in $domains) {
      $Group = Get-ADGroup -Filter { Name -like "*groupname*" } -Server $Domain 
      $Group | Get-ADGroupMember -Server $domain | Select @{
      Name="Domain";Expression={$Domain}},@{
      Name="Group";Expression={$Group.Name}}, name}
  
      $DisplayNames = $MembersOfSFDC_Groups.name
      $DisplayNames |Out-file (Join-Path $ScriptPath 'DisplayNames.txt')
  
      Get-content (Join-Path $ScriptPath 'DisplayNames.txt') |
      $displaynames | ForEach-Object {
      Get-ADUser -Server $LocalGC -Filter {Name -eq $_}  | 
      Select-Object -Property userPrincipalName} | 
      Out-File (Join-Path $ScriptPath 'upnOfSDFC_AD_GroupsMembers.txt')
  </code></pre>
  
  <p>But next problem is that this code is running about 30 min (Measure-Command cmdlet). We have a huge number of users across multiple domains.</p>
  
  <p>My question is how to <strong>improve</strong> my code to get user's UPN more <strong>faster</strong>?</p>
  
  <p>I know about <em>System.DirectoryServices.DirectorySearcher</em>, but don't know how to implementing this method with my txt-file (list of "names").</p>
  
  <p>Any help will be much appreciated. </p>