HOW TO: Delete AD group from SharePoint site collection using web services
This blog post is a contribution from Bharat Rathod, an engineer with the SharePoint Developer Support team.
I recently worked on a project where we had to delete an AD group which has permissions on a specific site collection. Since we had a limitation to not use server object model, I used web services to accomplish this.
SharePoint 2010 provides UserGroup.asmx web service out of the box. This has lot of very useful web methods. The web method I first tried was RemoveGroup(). For most of us, RemoveGroup() would seem the most appropriate web method and so I went ahead with it. The result was not what I expected. And I was presented with an error “Exception of type ‘Microsoft.SharePoint.SoapServer.SoapServerException’ was thrown”.
Upon further research, I found out that this web method deletes SharePoint groups and not AD groups. AD groups are treated as users in SharePoint and hence the error. Further reading through the UserGroup.asmx web service’s web methods, I boiled down to RemoveUserFromSite() web method call. I was able to delete the AD group remotely using a console application.
Here’s the sample code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DeleteADGroup.UserGroupService;
using Microsoft.SharePoint;
namespace DeleteADGroup
{
class Program
{
static void Main(string[] args)
{
UserGroup service = new UserGroup();
service.UseDefaultCredentials = true;
service.Url = "https://sp/_vti_bin/UserGroup.asmx";
service.RemoveUserFromSite(@"contoso\samplegroup");
Console.ReadKey();
}
}
}
Hope this short post was helpful!