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

How to Grant Permission to All Folders in a Document Library?

When you add a user to a document library in SharePoint Online, the user gets permission to access all folders that inherit permissions. How about folders with unique permissions? When granting permissions, make sure you select the checkbox, “Share everything in this folder, even items with unique permissions.”

To grant permission to all folders in a document library in SharePoint Online, you can use the following steps:

  1. Navigate to the document library where you want to grant permissions to all folders.
  2. Click on the gear icon in the upper-right corner, and then select “Document Library Settings”
  3. In the “Permissions and Management” section, click on “Permissions for this document library”.
  4. Click on the “Grant Permissions” button in the ribbon.
  5. Enter the email addresses or names of the people or groups you want to grant permissions to, and then select the level of permissions you want to grant (e.g., Read, Contribute, etc.).
  6. Set the “Share everything in this folder, even items with unique permissions.”, Click the “Share” button to grant the permissions.
     Share everything in this folder, even items with unique permissions.
  7. This will grant permissions to all folders within the document library.

SharePoint Online: Grant Permission to Folders using PowerShell

Granting permissions to all folders in a SharePoint Online library can be a tedious process if you have to do it manually for each folder. In this blog post, we’ll show you how to use PowerShell to quickly grant permissions to all folders in your SharePoint Online document library.

Here is the PowerShell to add users to each folder in the 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 = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Documents"
$UserAccount = "[email protected]"
$PermissionLevel= "Contribute"

#Function to Add User to Folder Permissions
Function Grant-SPOFolderPermission() {
    Param(
        [Microsoft.SharePoint.Client.Folder]$Folder, 
        [String]$UserAccount, 
        [String]$PermissionLevel
        )
    Try {

        #Check if Folder has unique permission already
        $Folder.ListItemAllFields.Retrieve("HasUniqueRoleAssignments")
        $Ctx.ExecuteQuery()

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

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

        #Get the role required
        $Role = $Ctx.web.RoleDefinitions.GetByName($PermissionLevel)
        $RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
        $RoleDB.Add($Role)
          
        #Assign permissions
        $UserPermissions = $Folder.ListItemAllFields.RoleAssignments.Add($User,$RoleDB)
        $Folder.Update()
        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
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery()
     
    #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 a given user with given access rights.

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 = "https://crescent.sharepoint.com/sites/Marketing"
$ListName="Documents"
$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'
} 

Granting permissions to a folder in SharePoint Online is explained in another post: How to Grant Folder Permissions in SharePoint Online using PowerShell?

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

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

Leave a Reply

Your email address will not be published. Required fields are marked *