Monday, September 19, 2016

SharePoint Online: Set Folder Permissions using PowerShell CSOM

Requirement: Change folder permissions in SharePoint Online using PowerShell.

PowerShell to change folder level permissions sharepoint online:
This PowerShell script breaks permissions of a folder and grants permissions using client side object model (CSOM).

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Variables
$SiteURL="https://crescent.sharepoint.com"
$FolderURL="/Project Documents/Active"
$GroupName="Team Site Members"
$UserAccount="Salaudeen@crescent.com"
$PermissionLevel="Edit"

Try {
    $Cred= Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
    $Web = $Ctx.web

    #Get the Folder
    $Folder = $Web.GetFolderByServerRelativeUrl($FolderURL)
    $Ctx.Load($Folder)
    $Ctx.ExecuteQuery()
    
    #Break Permission inheritence - Remove all existing list permissions & keep Item level permissions
    $Folder.ListItemAllFields.BreakRoleInheritance($False,$True)
    $Ctx.ExecuteQuery()
    Write-host -f Yellow "Folder's Permission inheritance broken..."
     
    #Get the SharePoint Group & User
    $Group =$Web.SiteGroups.GetByName($GroupName)
    $User = $Web.EnsureUser($UserAccount)
    $Ctx.load($Group)
    $Ctx.load($User)
    $Ctx.ExecuteQuery()

    #Grant permission
    #Get the role required
    $Role = $web.RoleDefinitions.GetByName($PermissionLevel)
    $RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
    $RoleDB.Add($Role)
         
    #Assign permissions
    $GroupPermissions = $Folder.ListItemAllFields.RoleAssignments.Add($Group,$RoleDB)
    $UserPermissions = $Folder.ListItemAllFields.RoleAssignments.Add($User,$RoleDB)
    $Folder.Update()
    $Ctx.ExecuteQuery()
    
    Write-host "Permission Granted Successfully!" -ForegroundColor Green  
}
Catch {
    write-host -f Red "Error Granting permission to  Folder!" $_.Exception.Message
}
and the result:
sharepoint online set folder permissions



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!


You might also like:

Related Posts Plugin for WordPress, Blogger...