Creating groups and adding users to the groups using PoweShell
When you are moving your site to production environment as a single click deployment package instead of site backup and restore you will be required to write scripts to achieve certain functionality. One is creating custom groups and adding users to that groups. The following Power-Shell script will be used to achieve this.
First we will create one xml file where it contains list of all groups and users in the given format.
The following script will read this xml file and create the groups and users in to the site.
First we will create one xml file where it contains list of all groups and users in the given format.
<?xml version="1.0" encoding="utf-8"?>
<Groups>
<Group name="Directors" description="">
<Users>
<User>Domain\director1</User>
</Users>
</Group>
<Group name="Coordinators" description="">
<Users>
<User>Domain\coordinator1</User>
</Users>
</Group>
</Groups>
The following script will read this xml file and create the groups and users in to the site.
#Get Site and Web objects
$siteurl = Get-SPSite
"http://machine-name:port/"
$site = Get-SPSite $siteurl
$web = $site.RootWeb
Write-Output "Current Site : " $site "and web : " $web
#Get XML file containing groups and associated
users
$groupsXML = [xml] (Get-Content
(".\UserGroup.xml"))
Write-Output "Adding groups to site"
$site
$groupsXML.Groups.Group | ForEach-Object
{
#Check to see
if SharePoint group already exists in the site collection
if
($web.SiteGroups[$_.name] -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($_.name, $web.CurrentUser, $null,
$_.description)
Write-Output "Added group" $_.name
}
Write-Output "Setting permission for group"
$_.name
#Get SharePoint
group from the site collection
$group =
$web.SiteGroups[$_.name]
$groupAssignment = new-object
Microsoft.SharePoint.SPRoleAssignment($group)
$groupRoleDefinition =
$web.Site.RootWeb.RoleDefinitions["Read"]
$groupAssignment.RoleDefinitionBindings.Add($groupRoleDefinition)
$web.RoleAssignments.Add($groupAssignment)
$web.Update()
#Add the users
defined in the XML to the SharePoint group
Write-Output "Adding users to group"
$_.name
$_.Users.User |
ForEach-Object {
if($_ -ne $null)
{
Write-Output "Adding " $_ " to group"
$_.name
$group.Users.Add($_, "", "",
"")
}
}
}
#Dispose of Web and Site objects
$web.Dispose()
$site.Dispose()
Comments
Post a Comment