In this blog, we will learn about how to remove bulk users from the entire site or from a certain SharePoint group , using CSOM.
Here, we are going to write a code to remove the bulk users from the various sites, which are based on the entries made on a certain SharePoint list. Find the process given below for what we need to do in order to achieve it.
- Create a SharePoint List named "MainList".
- Add the columns named - siteURL(single line of text), usertobeRemoved(single line of text), Output(single line of text) in the MainList
- Add a view in the list with the columns given above in order to retrieve only those columns from the list and name it as MainView.
Column Details
- siteURL(to be filled)- Site from where the user needs to be removed.
- usertobeRemoved(to be filled)- User name, who needs to be removed from the site(siteURL).
- Output(filled automatically)- Comments once the removal operation has been completed.
Once the steps given above have been done, create a new console app and add the code given below in order to make it run, as expected.
Console Application
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- string site = string.Empty;
- string usertobeRemoved = string.Empty;
- ClientContext context = new ClientContext("Site 1");
- Web web = context.Web;
- List oList = web.Lists.GetByTitle("MainList");
- View oView = oList.Views.GetByTitle("MainView");
- context.Load(oView);
- context.ExecuteQuery();
- CamlQuery camlQuery = new CamlQuery();
- camlQuery.ViewXml = oView.ViewQuery;
- ListItemCollection collListItem = oList.GetItems(camlQuery);
- context.Load(collListItem);
-
- context.ExecuteQuery();
-
- foreach (ListItem oListItem in collListItem)
- {
- context.Load(oListItem);
- site = Convert.ToString(oListItem["siteURL"]);
- usertobeRemoved = Convert.ToString(oListItem["usertobeRemoved"]);
- ClientContext context1 = new ClientContext(site);
- User user = context1.Web.EnsureUser(usertobeRemoved);
- try
- {
- context1.Web.SiteUsers.Remove(user);
- context1.ExecuteQuery();
- oListItem["Output"] = "Removed successfully";
- oListItem.Update();
- context.ExecuteQuery();
- }
- catch (Exception)
- {
- oListItem["Output"] = "Removed Failure";
- oListItem.Update();
- context.ExecuteQuery();
- }
- }
-
-
- }
- }
- }
Once the console app has been created, fill in the usertobeRemoved, siteURL in the Mainlist. Run the console app created and for verification purposes, the Output column will get updated, so that we can check whether the user has been removed or not from the site.