Create Security group and set permissions for Sharepoint list

28/01/2013 12:45

Start-SPAssignment -Global
#Get Site Groups

$webUrl="https://server/sitecollection"
$listToEdit=@("CustomList", "Pages")
$groupName="Authors"


$web = Get-SPWeb $webUrl

#Create Group with Read permission level

if($web.SiteGroups[$groupName] -eq $null)
{
 Write-Host "Creating $groupName group with Read permissions..."
 $web.SiteGroups.Add($groupName, $web.Site.Owner, $web.Site.Owner, "People with edit permissions for 'Pages' library and 'CustomList' list.");
 $group = $web.SiteGroups[$groupName]
  $group.AllowMembersEditMembership = $false
 $group.Update()
 
 $groupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)
 $groupRoleDefinition = $web.Site.RootWeb.RoleDefinitions["Read"]
 $groupAssignment.RoleDefinitionBindings.Add($groupRoleDefinition)
 $web.RoleAssignments.Add($groupAssignment)
}
else
{
 Write-Host "$groupName group already exists at $webUrl."
}

#Add testauthor to group
Write-Host "Adding 'Cham\testauthor' to '$groupName' group..."
$user = $web.Site.RootWeb.EnsureUser(“Cham\testauthor”)
$group.AddUser($user)
$web.Update()


#Set edit permission for Group for lists (Break inheritance)
foreach($listName in $listToEdit)
{
 $list = $web.Lists.TryGetList($listName);
 if($list -eq $null)
 {
  Write-Error "List '$listName' doesn't exist at $webUrl."
 }
 else
 {
  Write-Host "Breaking role inheritance for $listName ..."
  $list.BreakRoleInheritance($true)
   $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($group)
  Write-Host "Adding Edit rights 'Bijdragen' to list"
  $roleDefinition = $web.RoleDefinitions["Edit"]
  $assignment.RoleDefinitionBindings.Add($roleDefinition)
  $list.RoleAssignments.Add($assignment)
  $list.Update()
 }
}

Stop-SPAssignment -Global