22 February 2016

How do I - Get a list of email addresses of all users who belong to a given SharePoint security group?

One of mentees asked me how to extract the emails of all the owners of a given site.  With some Powershell magic and the use of the -ExpandProperty switch, this is actually quite easy.

$url = "http://{webapp}/sites/{site}";
$owners = Get-SPWeb $url | Select -ExpandProperty SiteGroups | Where {$_.Name.ToLower() -match ((Get-SPWeb $url).Title.ToLower() + " owners")} | Select -ExpandProperty Users | Select Email;
foreach ($owner in $owners)
{
   {do something with $owner.Email}
}

In the above script, we start off by setting the $url variable.  Then we make the big call to get the owners list of emails into $owners.
The command calls Get-SPWeb for the given URL.  The return of that is then piped to a Select command using the -ExpandProperty switch to expand the SiteGroups.  This would get you all site groups, but piping it to the Where command allows us to filter the returned groups down to the one we want.
The Where command is fed the name of the site group (in lower case) and is asked to match it against the spweb object's title (in lower case) with " owners" concatenated.  A couple of things to note:

  1. It is good practice to ALWAYS make the case of text the same on both sides of a text based comparison.  I prefer lower case, hence the dispersion of .ToLower() in my code.
  2. This part of the code does depend on default security groups being used in SharePoint.  This is 95% of the time the case, but you should be aware that different naming conventions may have been used for the name of the site owners group.
Now that we have the owners security group, the result is piped to another Select command expanding to return the users of that group.  Finally, we pipe to a Select statement that selects a single field i.e. the email address.

You now have an array of email addresses that can be iterated and used via the .Email field reference.

Enjoy
C

Microsoft Authentication Library (MSAL) Overview

The Microsoft Authentication Library (MSAL) is a powerful library designed to simplify the authentication process for applications that conn...