Tuesday, January 31, 2012

Powershell scripts to delete and add users and groups to Sharepoint 2010 site collections

I've put together the following scripts to first clear out all users from a Sharepoint site collection.  The scripts iterate through each group clearing out all of the users, as well as users not in a group.  The scripts then add users to each group.  All groups are passed in regardless of whether or not the group exists for the site collection.  If the group does not exist you will get a yellow warning message.  I've tried to make the scripts as straight forward to use as possible.  The scripts were created due to issues with Axceler ControlPoint not doing exactly what I would like to.  Look for a post soon for my full review of ControlPoint.

An example using the scripts below:

$url = "http://mysharepointsite.com/"
#Sitename is the preface for the groups
$sitename = "MySiteName"

# if no domain is specified, it defaults to DefaultDomain(change this for your environment)
#to add a user, add a comma and their name in quotes to the correct group
#AD groups can be added as well
$portalowners =  "user1", "user2"
$portalmembers = ""
$portalvisitors = "user3", "user4"
$portaldesigners = ""
$portalapprovers = "AD Group1", "AD Group2"

#include the addusers.ps1 file
$path = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
. (Join-Path -Path $path -ChildPath AddUsers.ps1)

Add-PSSnapin Microsoft.SharePoint.Powershell -erroraction silentlycontinue

#first clear out all users
ClearUsers $url

#set the group names
$OwnersGroup = $sitename + " Owners"
$MembersGroup = $sitename + " Members"
$VisitorsGroup = $sitename + " Visitors"
$DesignersGroup = "Designers"
$ApproversGroup = "Approvers"

#add the users
AddUsersToGroup $url  $OwnersGroup  $portalowners
AddUsersToGroup $url $MembersGroup  $portalmembers
AddUsersToGroup $url $VisitorsGroup $portalvisitors
AddUsersToGroup $url  $DesignersGroup $portaldesigners
AddUsersToGroup $url  $ApproversGroup $portalapprovers




The script with the functions to add and clear users:

File:  AddUsers.ps1

Function AddUsersToGroup ($url, $groupname, $userarray)
{
    # Get SPSite object
    $site = get-spsite $url -ErrorAction silentlycontinue

    if($site) {
        #check to see if the group exists on the site
        #added this because I want to use the same groups regardless of site template
        #for example the approvers group will always get passed in, but won't exist on a team site
        $groups = $site.RootWeb.SiteGroups
       
        $groupexists = $false
       
        foreach($group in $groups)
        {
            if( $group.Name.tolower() -eq $groupname.tolower())
            {
                $groupexists = $true
                break
            }
       
        }
       
        if($groupexists)
        {
            # Get SPGroup
            $group = $site.RootWeb.SiteGroups[$groupname]

            if($group) {
                # Loop through and add users
                foreach($user in  $userarray)
                {   
                    # Get user fields
                    $username = $user.trim()
                   
                    if($username.Length -gt 0)
                    {
                        #check if username contains a domain, if not add the default domain
                        #Edit the default domain to your domain
                        if($username.Contains("\"))
                        {
                        }else
                        {
                            $username = "DefaultDomain\" + $username
                        }
                       
                        Write-Host "Add user '$username' to group '$groupname' to site '$url'..."

                        # Add user to group
                        $group.AddUser($username , "", "", "")

                        Write-Host "User added" -ForeGroundColor Green
                       
                   
                    }
                   
               
                }
            }else
            {
                Write-Host "Can't open group '$groupname'" -ForeGroundColor Red
            }
        }else
            {
                Write-Host "Group '$groupname' does not exist on this site" -ForeGroundColor Yellow
            }
    } else
    {
        Write-Host "Can't open site '$url'" -ForeGroundColor Red
    }

    $site.dispose()
}


Function ClearUsers ($url)
{

    # Get SPSite object
    $site = get-spsite $url -ErrorAction silentlycontinue
   
    if($site) {
   
        #first remove users not in a group
        $removeUsers =  $site.RootWeb.Users
       
        #create an array to hold the users
        $UsersToDelete = @()
       
        #first build our list
         foreach ($removeUser in $removeUsers)
        {
            #don't remove the system account
            $test = $removeUser.LoginName.ToLower().Contains("system")
           
            if($test -eq $false)
            {
                $UsersToDelete += $removeUser.UserLogin
            }
        }
       
        $removeUsers = $UsersToDelete
       
        #now delete the users
        foreach ($removeUser in $removeUsers)
        {
                Write-Host "Removing individual user '$removeUser' from site '$url'..."
           
                $site.RootWeb.Users.Remove($removeUser)
        }
           
   
        # Get SPGroup
        $groups = $site.RootWeb.SiteGroups

        #now clear all users from groups
        foreach ($group in $groups)
        {
            $removeUsers = $group.Users
           
            $groupname = $group.Name
           
            foreach ($removeUser in $removeUsers)
            {
                    Write-Host "Removing user '$removeUser' from group '$groupname' from site '$url'..."
                    $group.RemoveUser($removeUser)
            }
           
        }

    }else
        {
              Write-Host "Can't open site '$url'" -ForeGroundColor Red
        }

       
    $site.dispose()

}


1 comment:

  1. Thanks for the script. There are some more possible ways to Delete Users from SharePoint Site Collection:

    1. You can delete users using SharePoint Web Interface
    2. Delete users from SharePoint site using PowerShell (Bulk Delete also possible)
    3. Remove users from SharePoint programmatically using C#

    Found these methods at SharePointDiary.com: Delete Users from SharePoint Site Collection

    ReplyDelete