Simple PS script to move users between SharePoint Security Groups

Today a user had a simple request – about 450 users were added to the wrong SharePoint Group.
They needed to be moved from the Members group to the Visitors group.

My first thought was to rename the groups and change permissions, but the user had already started the process and had moved about 100 of them manually before calling me.

So I had to move 350 users, and couldn’t rename and re-permission either Group.

My first though was to just dump a list of all the user ID’s from the Members Group using Powershell – I would paste them into the GUI to add them to the Visitors Group.

I used powershell to get the list of users:

$web = get-spweb "http://urlto.yourdomain.com/yourweb"
$group = $web.groups | where {$_.name -eq "Name of your Group" }
foreach ($user in $group.users) { $user.userLogin + ";" }

The above script dumped a bunch of user ID’s to the screen and my intention was to copy that right off the PowerShell screen. (Note I added the semicolon to make it easier to add the whole list in one copy/paste operation)

My first snag was that you can only paste in 200 users at a time, not a big deal, I did a few small groups.

Now I just needed to delete all the users from the Members group- Easy Right?
Well, it would be if I had less than 30- SharePoint only shows 30 members of a group at a time. You can select all 30 pretty easily, but I wanted to delete 350.

Back to Powershell
This script deletes everyone in the given group:

$web = get-spweb "http://urlto.yourdomain.com/yourweb"
$group = $web.groups | where {$_.name -eq "Name of your Group" }
foreach ($user in $group.users)
 { 
   $group.RemoveUser($user)
 }

Job Done.

Of course, at this point, I thought, shoot, I could have/should have just scripted the whole copy operation – can’t be that hard right?

$web = get-spweb "http://urlto.yourdomain.com/yourweb"
$SourceGroup = $web.groups | where {$_.name -eq "Name of your Source Group" }
$TargetGroup = $web.groups | where {$_.name -eq "Name of your Target Group" }
foreach ($user in $Sourcegroup.users)
 { 
   Write-Host "Moving $user from $SourceGroup to $TargetGroup"
   $TargetGroup.AddUser($user)
   #$SourceGroup.RemoveUser($user)
 }

Disclaimer – I haven’t tried this- by the time I got this far, I had already deleted all the users so this is more of a “for future reference” kind of script.

Ideally there might be a return value on .addUser that would let me know if it was successful, or you might run the script twice, the first time with the remove statement commented out, Then do a quick visual check that your Target Group has the users you need, then run it again to empty the SourceGroup.

One thought on “Simple PS script to move users between SharePoint Security Groups

Leave a Reply