SharePoint Online: Grant Permission to Each Folder in a Document Library using PowerShell

Requirement: Grant permission to all sub-folders in a SharePoint Online document library

PowerShell to Grant Permission to Each Folder in a SharePoint Online Document Library

SharePoint Online: Grant Permission to Folders using PowerShell

Here is the PowerShell to add a user to each folder in SharePoint Online list or document library.

#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"

#Set Config Variables
$SiteURL = ""
$ListName = "Documents"
$UserAccount = "[email protected]"
$PermissionLevel= "Contribute"

#Function To call a non-generic Load Method
Function Invoke-LoadMethod() {
            [Microsoft.SharePoint.Client.ClientObject]$Object = $(throw "Please provide a Client Object"), [string]$PropertyName
   $Ctx = $Object.Context
   $Load = [Microsoft.SharePoint.Client.ClientContext].GetMethod("Load") 
   $Type = $Object.GetType()
   $ClientLoad = $Load.MakeGenericMethod($Type)
   $Parameter = [System.Linq.Expressions.Expression]::Parameter(($Type), $Type.Name)
   $Expression = [System.Linq.Expressions.Expression]::Lambda([System.Linq.Expressions.Expression]::Convert([System.Linq.Expressions.Expression]::PropertyOrField($Parameter,$PropertyName),[System.Object] ), $($Parameter))
   $ExpressionArray = [System.Array]::CreateInstance($Expression.GetType(), 1)
   $ExpressionArray.SetValue($Expression, 0)

#Function to Add User to Folder Permissions
Function Grant-SPOFolderPermission() {
    Try {

        #Check if Folder has unique permission already
        Invoke-LoadMethod -Object $Folder.ListItemAllFields -PropertyName "HasUniqueRoleAssignments"

        If($Folder.ListItemAllFields.HasUniqueRoleAssignments -ne $true)
            #Break Folder Permission inheritence - Keep all existing folder permissions & Item level permissions
            Write-host -f Yellow "`tFolder's Permission inheritance broken..."

        #Get the SharePoint User
        $User = $Ctx.Web.EnsureUser($UserAccount)

        #Get the role required
        $Role = $Ctx.web.RoleDefinitions.GetByName($PermissionLevel)
        $RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
        #Assign permissions
        $UserPermissions = $Folder.ListItemAllFields.RoleAssignments.Add($User,$RoleDB)
        Write-host -f Green "`tAdded User to Folder Permissions!"
    catch {
        write-host "Error in Grant Permissions: $($_.Exception.Message)" -foregroundcolor Red

#Get Credentials to connect
$Cred = Get-Credential
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
    #Get the List
    $List = $Ctx.web.Lists.GetByTitle($ListName) 
    #Get Sub-Folders of the List
    $SubFolders = $List.RootFolder.Folders
    #Iterate through Each Sub-Folder
    ForEach($Folder in $SubFolders)
        #Exclude "Forms" and Hidden folders
        If(($Folder.Name -ne "Forms") -and (-Not($Folder.Name.StartsWith("_"))))
            #Get the Folder's Server Relative URL
            Write-host -f Yellow "Granting Permissions on Folder:"$Folder.Name
            Grant-SPOFolderPermission -Folder $Folder -UserAccount $UserAccount -PermissionLevel $PermissionLevel
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red

This script recursively loops through each sub-folder in the given list or library and changes folder permissions by adding given user with given access rights. Managing folder permissions in SharePoint Online is discussed in my another article: SharePoint Online: Set Folder Permissions using PowerShell

PnP PowerShell to Add User to All Folders in a Document Library:

The Set-PnPListItemPermission cmdlet breaks the permission inheritance of the item, if it’s not broken already and adds/removes permissions based on the given parameters.

#Set Variables
$SiteURL = ""
$ParentFolderURL = "/Shared Documents" #Site Relative Path of the document Library
$UserAccount = "[email protected]"
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get all Folders from the given location - Exclude Hidden
$AllFolders= Get-PnPFolderItem -ItemType Folder -FolderSiteRelativeUrl $ParentFolderURL | Where {($_.Name -ne "Forms") -and (-Not($_.Name.StartsWith("_")))}

#Iterate through each Folder
ForEach($Folder in $AllFolders)
    Write-host ("Granted Permission to '{0}' at {1} " -f $Folder.Name,$Folder.ServerRelativeUrl)
    #Grant Contribute permissions to the Folder
    Set-PnPListItemPermission -List $ListName -Identity $Folder.ListItemAllFields -User $UserAccount -AddRole 'Contribute'

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

2 thoughts on “SharePoint Online: Grant Permission to Each Folder in a Document Library using PowerShell

  • February 22, 2021 at 11:49 AM

    I have the problem grant permissions

    Error Granting permission to Folder! Excepción al llamar a “ExecuteQuery” con los argumentos “0”: “No se encuentra el nivel de permisos.”

    What’s the problem?

  • March 30, 2020 at 1:01 AM

    This is great thanks. Do you have a script that creates a batch of folders in a document library each with permissions for site owners and a single specified user (different for each folder) – all from a CSV (where first col is folder name and second is named accounts for permissions)?


Leave a Reply