PowerShell Script – list all SharePoint group members


A quick script to query  site collections in a web application for SharePoint group and list all the members of that group and export into an CSV file. In the below example I am looking for “Power Users” group and list all the members of that group

$sites = Get-SPWebApplication http://intranet.contoso.com | Get-SPSite -limit all
"Site Collection`t Group`t User Name`t User Login" | out-file groupmembersreport.csv
foreach($site in $sites)
{
	$sitegroup = $site.RootWeb.SiteGroups |?{$_.Name -EQ "Power Users"}
	foreach($user in $sitegroup.Users)
		{	
		"$($site.url) `t $($sitegroup.Name) `t $($user.displayname) `t $($user) " | out-file groupmembersreport.csv -append
		}
$site.Dispose()
}

If you are interested in querying all the groups in the site collections and list all the members

# if you want to query all the site collections and its groups members then un comment line 4 and comment line 5
# $sites = get-spsite -limit All
$sites = Get-SPWebApplication http://intranet.contoso.com | Get-SPSite -limit all
"Site Collection`t Group`t User Name`t User Login" | out-file groupmembersreport.csv
foreach($site in $sites)
{
	foreach($sitegroup in $site.RootWeb.SiteGroups)
        {
	  foreach($user in $sitegroup.Users)
	 	{	
		"$($site.url) `t $($sitegroup.Name) `t $($user.displayname) `t $($user) " | out-file groupmembersreport.csv -append
		}
          }
$site.Dispose()
}

You can also write in a single line if you quickly want to query for a single site collection

Get-Spweb http://intranet.contoso.com | Select -ExpandProperty SiteGroups | Where {$_.Name -EQ "Power Users"} | Select -ExpandProperty Users | Select Name, userlogin, Email