I was chatting with my buddy and fellow MVP, Todd Klindt, the other day and he was asking if I had a custom command that would allow him to quickly delete all the users added to a site collection. For his purposes he needed this to troubleshoot an issue he was having with a site collection that contained many thousands of users.
I figured this would be pretty easy to do – a simple while loop with a conditional check for site administrators to prevent them from being deleted so I quickly typed out the following code during our IM conversation:
1using (SPSite site = new SPSite(url))
2using (SPWeb web = site.OpenWeb())
3{
4 int offsetIndex = 0;
5 while (web.SiteUsers.Count > offsetIndex)
6 {
7
8 if (web.SiteUsers[offsetIndex].IsSiteAdmin || web.SiteUsers[offsetIndex].ID == web.CurrentUser.ID)
9 {
10 offsetIndex++;
11 continue;
12 }
13 web.SiteUsers.Remove(offsetIndex);
14 }
15}
We can’t use a for loop for this because we’re modifying the collection and that would result in an error so we need to use a while loop and just keep deleting until there’s no more to delete. But, we have to watch out for site administrators as we can’t directly delete them in this fashion (and it’s a good idea to keep them regardless) so we use an offset that gets incremented whenever we hit an administrator. We also can’t delete the current user so I check for that as well.
One thing to note is that if you have a lot of users (Todd was dealing with 17,000) then it will run real slow – he was seeing about 300 deleted per hour with progressively more as the size dwindled – so be patient 🙂
I figured since I had the code that I might as well turn it into a new stsadm command so I created gl-deleteallusers
. There’s not really much to this command – it just takes in a single URL parameter which points to your site collection. I thought about adjusting this so that you could delete users from a specific web that had broken inheritance but I didn’t really have time. Here’s the help output:
C:\>stsadm -help gl-deleteallusers
stsadm -o gl-deleteallusers
Deletes all site collection users. Will not delete site administrators.
Parameters:
-url <site collection url>
The following tables summarizes the command and its parameters:
Command Name | Availability | Build Date |
---|---|---|
gl-deleteallusers | WSS v3, MOSS 2007 | Releaesd: 7/23/2008 |
Parameter Name | Short Form | Required | Description | Example Usage |
---|---|---|---|---|
url | Yes | The URL of the site collection of which the users will be deleted. If a sub-site of the site collection is passed in it will only look at the site collection itself and ignore the sub-site information. | -url http://portal/ |
Using the command is real simple – the following will delete all users, except site administrators, from the http://portal/sites/site1 site collection:
stsadm -o gl-deleteallusers -url http://portal/sites/site1