Keep it simple: Adding bulk set of users to a SharePoint Group using REST API

Large enterprises always require bulk operations to make things faster and easier. Recently I faced a situation where hundreds of users needed to be added to SharePoint Groups. This is a time consuming task in large SharePoint setups when you have to manually add users one by one. No ! Manual approach isn’t going to work for such things.

rube-goldberg-machine-100593802-primary.idge

REST API in SharePoint can be used in this scenario to cut down the efforts and time from hours or even days to few seconds. with this post I will discuss the way I achieved this goal so that you can follow me if you are in such a situation.

Background: I have an excel sheet filled with all required users with the UserName column. This excel spreadsheet is uplaoded to the SiteAssets library. This code will be looking at this library and read the excel sheet to pick the users from it.  Simple as that !

Change the site URL attribute’s value to reflect yours and you are good to go



var i;
var l;
var a1;
var user;
var spGroup;
function AddUserFromExcel()
{
l=1;
var Excel;
Excel = new ActiveXObject(“Excel.Application”);
Excel.Visible = false;
for(l=1;l<3;l++)
{
a1=Excel.Workbooks.Open(“http://mantososp/SiteAssets/Users.xlsx?Web=1”).ActiveSheet.Cells(l,1).Value;
var a4=”Domain\\”+a1;
var clientContext = new SP.ClientContext.get_current();
var web=clientContext.get_web();
var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(4990);
user=web.ensureUser(a4);
var userCollection=spGroup.get_users();
userCollection.addUser(user);
clientContext.load(user);
clientContext.load(spGroup);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);


function onQuerySucceeded()
{
alert(‘success’);
}
function onQueryFailed()
{
alert(‘Request failed.’);
}
}
}



var i;
var l;
var a1;
var user;
var spGroup;
function AddUserFromExcel()
{
l=1;
var Excel;
Excel = new ActiveXObject(“Excel.Application”);
Excel.Visible = false;
for(l=1;l<3;l++)
{
a1=Excel.Workbooks.Open(“http://mantososp/SiteAssets/Users.xlsx?Web=1”).ActiveSheet.Cells(l,1).Value;
var a4=”Domain\\”+a1;
var clientContext = new SP.ClientContext.get_current();
var web=clientContext.get_web();
var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(4990);
user=web.ensureUser(a4);
var userCollection=spGroup.get_users();
userCollection.addUser(user);
clientContext.load(user);
clientContext.load(spGroup);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);


function onQuerySucceeded()
{
alert(‘success’);
}
function onQueryFailed()
{
alert(‘Request failed.’);
}
}
}

Advertisement