SharePoint: Powershell scripts for reading, deleting and adding Groups from a Site Collection

Here are couple of Powershell scripts to play around with the SharePoint groups and users.

Reading All the Users and Groups in a Site Collection

$site = Get-SPSite "SiteCollection URL" 
$groups = $site.RootWeb.sitegroups
foreach ($grp in $groups) {"Group: " + $; foreach ($user in $grp.users) {"" + $user.loginname + ""} }

Adding Groups, Permission and Users to the respective groups to a Site Collection:

Function AddSnapIn()
#handles exceptions caused by trying to add a snapin
Trap [Exception]

#Check that the required snapins are available , use a comma delimited list.
# ("Microsoft.SharePoint.PowerShell", "Microsoft.Office.Excel")
$RequiredSnapIns = ("Microsoft.SharePoint.PowerShell");
ForEach ($SnapIn in $RequiredSnapIns)
if ( (Get-PSSnapin -Name $SnapIn -ErrorAction SilentlyContinue) -eq $null )
Add-PsSnapin $SnapIn
function AddPermissionLevel ($web, $groupName, $permLevel)
$spGroup = $web.SiteGroups[$groupName]

$assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($spGroup)
$role = $web.RoleDefinitions[$permLevel]


#Get Site and Web objects
$site = Get-SPSite "URL to Site Collection"
$web = $site.RootWeb

#Get XML file containing groups and associated users
$groupsXML = [xml] (Get-Content ("GroupsandUsers.XML"))

#Walk through each group node defined in the XML file
$groupsXML.Groups.Group | ForEach-Object {
#Check to see if SharePoint group already exists in the site collection
if ($web.SiteGroups[$] -eq $null)
#If the SharePoint group doesn't exist already - create it from the name and description values at the node
$newGroup = $web.SiteGroups.Add($, $web.CurrentUser, $null, $_.description)
AddPermissionLevel -web $web -groupName $ -permLevel $_.permLevel
#Get SharePoint group from the site collection
$group = $web.SiteGroups[$]
#Uncomment following three lines if you want to add another groups as current group owner
#$OwnerGroup = $web.SiteGroups["PMO_Owners"]
#$group.Owner = $OwnerGroup
#Add the users defined in the XML to the SharePoint group
$_.Users.User | ForEach-Object {
$group.Users.Add($_, "", "", "")

#Dispose of Web and Site objects
Remove-PsSnapin Microsoft.SharePoint.PowerShell

The accompanying XML file i.e. “GroupsandUsers.XML” should look like this:


Removing Groups from SiteCollection in Bulk

$spWeb = Get-SPWeb "SiteCollection URL"
$spGroups = $spWeb.SiteGroups
#Add groups in the following array as per your requirement
$groups = ("GroupName1", "GroupName2","GroupName3","GroupName4","GroupName5","GroupName6","GroupName7","GroupName8")
ForEach($group in $groups) {


Post navigation

Leave a Reply

Your email address will not be published. Required fields are marked *