Posted on:
Categories: SharePoint;PowerShell
Description:

 ​I was recently tasked with determining the group membership of several users across numerous different site collections. This was another perfect opportunity to use PowerShell. The following script can be scoped at the Web Application, Site Collection or Web and will give you all group memberships for the specified user in that scope.

Function GetGroupMemberships ($User, $Url, $Scope){
  
 Switch ($Scope){
 
 "WebApplication"{
 
  $WebApp = Get-SPWebApplication $URL
  
  foreach($SPSite in $WebApp.Sites){
   Write-Host -ForegroundColor Cyan "Checking" $SPSite.Url
   $userName = Get-SPUser -identity $User -web $SPSite.Url -ErrorAction silentlycontinue
   $groups = @()

   $groupMemberships = $userName.Groups |select Name
   foreach($group in $groupMemberships){
    $groups+=$group.Name
   }

   foreach($SPWeb in $SPSite.allwebs){
    foreach($group in $SPWeb.Groups){
      foreach($groupName in $groups)
      if ($groupName -eq $group.Name){
       Write-Host $User "is a member of " -nonewline
       Write-Host -foregroundcolor Green $groupName "" -nonewline
       Write-Host "in " -nonewline
       Write-Host -foregroundcolor Yellow $SPWeb.URL
      }
      }
    }
   }
  }
 
 }
 
 "Site"{
 
  $SPSite = Get-SPSite $Url

  $user = Get-SPUser -identity $User -web $Url
  $groups = @()

  $groupMemberships = $user.Groups |select Name
  foreach($group in $groupMemberships){
   $groups+=$group.Name
  }

  foreach($SPWeb in $SPSite.allwebs){
   foreach($group in $SPWeb.Groups){
     foreach($groupName in $groups){
     if ($groupName -eq $group.Name){
      Write-Host $User "is a member of " -nonewline
      Write-Host -foregroundcolor Green $groupName "" -nonewline
      Write-Host "in " -nonewline
      Write-Host -foregroundcolor Yellow $SPWeb.URL
     }
     }
   }
  }
 }
 
 "Web"{
   $SPWeb = Get-SPWeb $Url

   $user = Get-SPUser -identity $User -web $Url
   $groups = @()

   $groupMemberships = $user.Groups |select Name
   foreach($group in $groupMemberships){
    $groups+=$group.Name
   }

   foreach($group in $SPWeb.Groups){
    foreach($groupName in $groups){
     if ($groupName -eq $group.Name){
      Write-Host $User "is a member of " -nonewline
      Write-Host -foregroundcolor Green $groupName "" -nonewline
      Write-Host "in " -nonewline
      Write-Host -foregroundcolor Yellow $SPWeb.URL
     }
    }
   }
  }
 }
}

GetGroupMemberships -User "Domain\UserName" -Url "http://domain.com" -Scope "WebApplication"
#GetGroupMemberships -User "Domain\UserName" -Url "http://domain.com" -Scope "Site"
#GetGroupMemberships -User "Domain\UserName" -Url "http://domain.com" -Scope "Web"