Wednesday, August 17, 2011

Grant folder permission(SharePoint) using powershell script

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
 $site = new-object Microsoft.SharePoint.SPSite("http://myserver/")
 $web = $site.OpenWeb()
 function GrantGroupPermission($groupName)
 {
  [Microsoft.SharePoint.SPGroupCollection]$spgroups = $web.SiteGroups
  [Microsoft.SharePoint.SPGroup]$spgroup = $groups[$groupName]
  $sproleass=new-object Microsoft.SharePoint.SPRoleAssignment([Microsoft.SharePoint.SPPrincipal]$spgroup)
  $folder.BreakRoleInheritance("true")
  $sproleass.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
  $folder.RoleAssignments.Add($sproleass);
  Write-Host "Permission provided for group ", $groupName
 }
 function GrantUserpermission($userName)
 {
  [Microsoft.SharePoint.SPUserCollection]$spusers=[Microsoft.SharePoint.SPUserCollection]$web.SiteUsers
  [Microsoft.SharePoint.SPUser]$spuser=$spusers[$userName]
  $sproleass=new-object Microsoft.SharePoint.SPRoleAssignment([Microsoft.SharePoint.SPPrincipal]$spuser)
  $folder.BreakRoleInheritance("true")
  $sproleass.RoleDefinitionBindings.Add($web.RoleDefinitions["Contribute"])
  $folder.RoleAssignments.Add($sproleass);
  Write-Host "Permission provided for user ", $userName
 }
 $doclib=[Microsoft.SharePoint.SPDocumentLibrary]$web.Lists["Shared Documents"]
 $foldercoll=$doclib.Folders;
 foreach($folder in $foldercoll)
 {
  Write-Host $folder.Name
  if($folder.Name.Equals("f2"))
  {
   GrantUserPermission("raj")
  }
 
 }
 Write-Host "Completed...."
 $web.Close()
 $site.Dispose()

3 comments:

  1. Should
    [Microsoft.SharePoint.SPGroup]$spgroup = $groups[$groupName]

    be actually

    [Microsoft.SharePoint.SPGroup]$spgroup = $spgroups[$groupName]

    because i cant see a variable by that name $groups anywhere else in the code

    ReplyDelete
    Replies
    1. yes... It was a spelling mistake while posting :)

      Delete
  2. How do you do the reverse .. remove an inherited group permission from a folder?

    ReplyDelete