Friday, June 27, 2014

Create Multiple SPGroups in all the subsites if the SPGroups doesn't exist

For few hours of thinking, I have created the script and here i am sharing it which may be helpful for the others.



#Create an XML with all the details for the new Groups and menbers for the groups

<?xml version="1.0"?>
<Groups>
<Group name="GroupA" description="Test GroupA" PermissionLevel="Contribute">
<Users>
<User>Domain\Member1</User>
<User>Domain\Member2</User>
<User>Domain\Member3</User>
</Users>
</Group>
<Group name="GroupB" description="Test GroupB" PermissionLevel="Read">
<Users>
<User>Domain\Member1</User>
<User>Domain\Member2</User>
<User>Domain\Member3</User>
<User>Domain\Member4</User>
<User>Domain\Member5</User>
</Users>
</Group>




#Now create a script file with the below script

#Get Site and Web objects
$site = get-spsite https://portal/site/Test/

#Get all the sub sites under the web
foreach($web in $site.allwebs)
{
#Get XML file containing groups and associated users
$groupsXML = [xml] (Get-Content ("C:\Temp\Groups.XML"))

#Walk through each group node defined in the XML file
$groupsXML.Groups.Group | ForEach-Object {

[string]$permissionLevel = $_.PermissionLevel

#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
$web.SiteGroups.Add($_.name, $web.CurrentUser, $null, $_.description)
$newGroup = $web.SiteGroups[$_.name]
}

#Get SharePoint group from the site collection
$group = $web.SiteGroups[$_.name]

#Add the users defined in the XML to the SharePoint group
$_.Users.User | ForEach-Object {
$group.AddUser($_, "", "", "")
}

$roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)
$roleDefinition = $web.Site.RootWeb.RoleDefinitions[$permissionLevel]
$roleAssignment.RoleDefinitionBindings.Add($roleDefinition)

$web.RoleAssignments.Add($roleAssignment)

Write-Host "Group Name: "$group" Created at site: " $web.url
}

#Dispose of Web and Site objects
$web.Dispose()
$site.Dispose()
}


No comments:

Post a Comment