How to get the total number of external users of a Office 365 tenant in SharePoint online/Office 365?

Hello SharePointers,

In this blog, we will see how to get the total number of external users of a Office 365 tenant in SharePoint online/Office 365. Here are the code below

List<ExternalShareDetails> shares = new List<ExternalShareDetails>();
string adminRealm = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri);
var adminToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, adminRealm).AccessToken;
using (var cc = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), adminToken))
{

var tenant = new Office365Tenant(cc);
cc.Load(tenant);
cc.ExecuteQuery();

int position = 0;
bool count = true;
while (count)
{
var externalUsers = tenant.GetExternalUsersForSite(“http://mysharepiointsite/, position, 50, String.Empty, SortOrder.Descending);
cc.Load(externalUsers, i => i.TotalUserCount);
cc.Load(externalUsers, i => i.ExternalUserCollection);
cc.ExecuteQuery();

foreach (var extUser in externalUsers.ExternalUserCollection)
{
position++;
shares.Add(new ExternalShareDetails()
{
AcceptedAs = extUser.AcceptedAs.ToLower(),
DisplayName = extUser.DisplayName,
InvitedAs = extUser.InvitedAs.ToLower(),
InvitedBy = (String.IsNullOrEmpty(extUser.InvitedBy)) ? null : extUser.InvitedBy.ToLower(),
UserId = extUser.UserId,
WhenCreated = extUser.WhenCreated
});
}

//determine if we have more pages to process
count = (externalUsers.TotalUserCount > position);
}
}

Happy SharePointing Folks 🙂

Leave a Reply

Your email address will not be published.