How to get a list of groups for user

There are times when I need to look at a list of groups to which a user belongs. To make this an easier proposition, you can use the cmdlet below to produce the list, you can specify a single user or a list of comma separated users.

When originally looking for this solution, I ran across the following link if you want to refer to that post.

Param (
   [Parameter(Mandatory=$true,ValueFromPipeLine=$true)]
   [Alias("ID","Users")]
   [string[]]$User
)
Begin {
   Try { Import-Module ActiveDirectory -ErrorAction Stop }
   Catch { Write-Host "Unable to load Active Directory module, is RSAT installed?"; Break }
}
 
Process {
   ForEach ($U in $User)
   {  $UN = Get-ADUser $U -Properties MemberOf
      $Groups = ForEach ($Group in ($UN.MemberOf))
      {   (Get-ADGroup $Group).Name
      }
      $Groups = $Groups | Sort
      ForEach ($Group in $Groups)
      {  New-Object PSObject -Property @{
            Name = $UN.Name
            Group = $Group
         }
      }
   }
}

Leave a Reply