SharePoint Online: Set Folder Permissions using PowerShell

Requirement: Change folder permissions in SharePoint Online using PowerShell.

How to Set folder level permissions in SharePoint Online?

One of the most common SharePoint Online administrative tasks is managing folder permissions. In this blog post, we will show you how to use PowerShell to set folder permissions for a SharePoint Online site. We will also cover how to adjust the permissions for folders in SharePoint Online through the web browser interface. Stay tuned!

How to give unique permission to a folder in SharePoint Online? To manage folder permissions such as Add or Restrict in SharePoint Online, follow these steps:

  1. Navigate to your SharePoint Online document library where the target folder is located. 
  2. Click on “Manage access” either from the details pane or from the context menu of the folder.restrict permissions to folder sharepoint online
  3. In the Details pane, click on the “Advanced” link. This takes you to the “Advanced Permissions” page.set permission to folder in sharepoint online
  4. From the ribbon, click on the “Stop Inhering Permissions” button and confirm the prompt (If the folder is inheriting permissions from its parent).
  5. Now, You’ll get the list of users and groups who already have permissions on the folder. When you break the permission, SharePoint copies permissions from its parent (List/library in our case!). Click on the “Grant Permission” button from the ribbon to add users to the folder. 
    powershell sharepoint online add permission to folder
  6. Enter the names of the users and groups you want to add permission to the folder and select the appropriate permission level by clicking on the “Show Options” link on the share page. Click on the “Share” button to add permission to the folder.
    sharepoint online set permissions on folder

Similarly, to restrict access to the folder in SharePoint Online, select all the users in the folder permissions page and click on “Remove User Permissions”.

Alright! Let’s use PowerShell to add users to a SharePoint Online folder.

PowerShell to change folder level permissions SharePoint Online:

Can you restrict access to folders in SharePoint Online with PowerShell? Of course, yes! Let’s add permission to the SharePoint Online folder using PowerShell. This PowerShell script breaks permissions of a folder and grants permissions using the 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" #Or https://crescent.sharepoint.com/sites/Marketing
$FolderURL="/Project Documents/Active" #Or /sites/Marketing/Project Documents/Active - Server Relative URL of the Folder!
$GroupName="Team Site Members"
$UserAccount="[email protected]"
$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 of the folder - Keep all existing folder 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()

    #sharepoint online powershell set permissions on folder
    #Get the role required
    $Role = $web.RoleDefinitions.GetByName($PermissionLevel)
    $RoleDB = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($Ctx)
    $RoleDB.Add($Role)
         
    #add sharepoint online group to folder using powershell
    $GroupPermissions = $Folder.ListItemAllFields.RoleAssignments.Add($Group,$RoleDB)

    #powershell add user to sharepoint online folder
    $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
}

This PowerShell breaks permission inheritance of the folder and grants access to a user and group. Here is the result of the change in the folder permissions:

sharepoint online set folder permissions

PnP PowerShell to Change Folder Permissions in SharePoint Online

To grant permission to a folder in SharePoint Online, use this PnP PowerShell:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName="Documents"
$FolderServerRelativeURL = "/sites/marketing/Shared Documents/2019"
$UserAccount = "[email protected]"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get the Folder from URL
$Folder = Get-PnPFolder -Url $FolderServerRelativeURL
    
#Grant Permission to a Folder
Set-PnPListItemPermission -List $ListName -Identity $Folder.ListItemAllFields -User $UserAccount -AddRole 'Contribute'

How to restrict access to a folder in SharePoint Online?

You can also restrict a SharePoint Online folder access using the Set-PnPFolderPermission cmdlet. Here is an example:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$ListName ="Branding"
$FolderServerRelativeURL = "/Sites/Marketing/Branding/2020"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#PowerShell to add user to sharepoint online folder
Set-PnPfolderPermission -List $ListName -identity $FolderServerRelativeURL -User "[email protected]" -AddRole "Edit"

#To remove user, use: Set-PnPfolderPermission -List $ListName -identity $FolderSiteRelativePath -User "[email protected]" -RemoveRole "Edit"

How to change folder permissions in SharePoint Online with PnP PowerShell?

Similarly, to grant permission to a SharePoint Online group, use:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$ListName ="Branding"
$FolderServerRelativeURL = "/Sites/Marketing/Branding/Active"
  
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
 
#Grant folder permissions to SharePoint Group
Set-PnPfolderPermission -List $ListName -identity $FolderServerRelativeURL -AddRole "Edit" -Group "Marketing Members"

This script breaks the permission inheritance of the given folder and adds or removes permission to the folder to the given user or group. Similarly, you can set permissions to AD Groups using its name as a parameter value to “user”. Here is another post on SharePoint Online: PowerShell to Get Folder Permissions

How do I restrict access to a document library in SharePoint Online?

Browse to the document library >> Click on Settings >> “Library Settings” >> Click on the “Permissions for this document library” >> Click on the “Stop Inheriting Permissions”. Now you can add or remove users and groups to the document library to restrict permissions.
More info: Set Permissions to a Document Library in SharePoint Online

How do I make a SharePoint Online folder accessible to everyone?

Just grant access to the “Everyone” group on the folder! How to Grant Access to Everyone in SharePoint Online?

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!

36 thoughts on “SharePoint Online: Set Folder Permissions using PowerShell

  • Fantastic!

    I’m trying to assign permissions to 3 folders within multiple folders in SP – would the scripts you have provided work for that?

    i.e. folder 1/ folder 2/ folder a
    folder 1/ folder 2/ folder b
    folder 1/ folder 2/ folder c

    I want to set specific permissions on folders a, b & c

    Thanks

    Reply
  • Ah brilliant that worked. Your site has been very helpful. My main issue has been knowing what to use to connect to SharePoint. I was using a mixture of the management shell & PNP.Powershell and I was having loads of issues. I’m sticking to PNP.Powershell, as that seems to do everything I need. It’s just finding how to use the commands 🙂

    Reply
  • Hi, thanks very much, I’ll give it a go 🙂

    Reply
  • Hello,
    I have this error : File not found.
    This is my cmdlt :

    foreach($line in $ListeUser){
    $Nom = $line.Nom
    Set-PnPFolderPermission -List ‘Toto’ -Identity ‘Toto\$Nom’ -User ‘$line.Compte’ -AddRole ‘Contribute’
    }

    Thanks

    Reply
    • Can you check the Identity parameter? It should be the server relative URL of the folder! E.g. /sites/marketing/documents/2021

      Reply
  • Hello,

    I just can’t get this to work 🙁
    I want to be able to prevent Teams members of a SharePoint site being able to edit the site pages. I can do it using the GUI, but not via PowerShell.
    This is what I’m doing:

    =======================================
    $SiteURL = “https://mysp.sharepoint.com/sites/Accounts”
    $ListName =”Forms”
    $FolderServerRelativeURL = “/Sites/Accounts/SitePages”

    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive

    #Grant folder permissions to SharePoint Group
    Set-PnPfolderPermission -List $ListName -identity $FolderServerRelativeURL -RemoveRole “Edit” -Group “Accounts Members”
    ========================================

    What I’m not sure of if the ListName is correct or the relative URL.
    The web address for the Site Pages Forms is:
    https://mysp.sharepoint.com/sites/Accounts/SitePages/Forms/ByAuthor.aspx

    I’m assuming this is the same for all SharePoint Online sites.
    Obviously, my url isn’t mysp.sharepoint.com 🙂

    Thanks for any help.

    David

    Reply
  • Hi.
    I used your additional update although it still shows Get-PnPFolder: File Not Found.
    In the -SetPnPItemListPermission with the -Identity attribute, is there something to update or not after this.

    Reply
  • Salaudeen, your posts are well done, thank you!

    I’m making a script (1800+ lines) that assigns unique permissions to folders based on security groups in O365. Recently in my testing I’m getting errors when I assign “Restricted View” to some folders around the end of the script. If I assign by hand sometimes it works fine other times it doesn’t. It use to work fine as all of my previous scripts have the appropriate right set. The command I’m using is:

    Set-PnPFolderPermission -List “Shared Documents” -Identity “Shared Documents/General/Private Stuff” -User Proj-Special-Access -AddRole “Restricted View”

    Any help would be super appreciated.

    Reply
    • Some additional information: After I’ve run the script and my login has expired I go back to my script and do the following (quotes indicate exact commands):

      Execute initial portion that sets variables
      “Connect-MicrosoftTeams”
      Get team name and groupID variables
      “Connect-PnPOnline -ClearTokenCache -SPOManagementShell $SharePointSiteName #This logs in with MFA
      Execute permission command in original post

      This executes properly.

      Reply
  • Thank your for your scripts, Salaudeen you are so great doing this.
    I was having issues, but using the -Includes ListItemAllFields resolved it:
    $Folder = Get-PnPFolder -Url $FolderServerRelativeURL -Includes ListItemAllFields

    best regards!

    Reply
  • Is there a way to grant access to all SharePoint Online sites for an account using Power shell

    Reply
  • Thank you! Great article
    Any idea how to give permissions in a folder to a sharepoint group? I tried -group parameter but It gives an error like: Set-PnPFolderPermissions: It can’t find this permission level (my translation from spanish)

    Reply
    • Group parameter is meant for “SharePoint Groups” (Not AD Group!), If you want to grant permission to AD group (Security/Office 365 groups), use -User parameter with the group name.

      Reply
  • It doesnt seem to work with external users…

    Reply
  • Hello.
    I am getting the error: Exception calling “ExecuteQuery” with “0” argument(s): “Can not find the principal with id: 259.”
    for line 48 when $Ctx.ExecuteQuery() is being executed to add the permisison to the folder.

    How can this be resolved?

    Thanks in advance

    Reply
  • I’m receiving the following:
    Error Granting permission to Folder! Exception calling “ExecuteQuery” with “0” argument(s): “File Not Found.”

    Any help, much appreciated.

    Reply
    • Here the Folder URL should be relative URL. Say: Your Site collection is at: https://yourdomain.sharepoint.com/sites/sales/” and your folder is at: /documents/active”, then the relative URL should be: “/sites/sales/documents/active”

      Reply
    • Same problem for me – trying to loop through a number of “subsites” and setting the permission on a folder in their default documents library.

      When using this advise: “Here the Folder URL should be relative URL. Say: Your Site collection is at: https://yourdomain.sharepoint.com/sites/sales/” and your folder is at: /documents/active”, then the relative URL should be: “/sites/sales/documents/active”
      powershell.html#ixzz5dQ8JqxMa”

      I get error: Error Granting permission to Folder! Exception calling “ExecuteQuery” with “0” argument(s): “File Not Found.” when using

      Reply
    • Please note, your document library’s name could be “Documents” while the actual URL is: /shared documents/, So check if the given relative URL is valid in $FolderURL parameter!

      Reply
    • Hi again. It seem that the command
      $Group =$Web.SiteGroups.GetByName($GroupName)
      gets the SharePoint Groups only. What can we do if we want to get and Active Directory Synched group?

      Reply
    • Trying to do the same but I’m not using AD Connect. I’ve created groups in the admin portal and they are referred to as a domain group when assigned just through the Web gui. Is my Domain just my onmicrosoft.com tennant that is created? Sorry if this is a silly question. And thank you for this tutorial.

      Reply
  • I have given Full Control to the spesific user but I can not see any changes even after logging from that spesific user to access the folder. The user can not change, delete or edit the folder but strangely it shows Full Control in the folder permission list.

    Reply
  • Is there a way to use this code to remove the permission if my folder already has the permission?

    Reply
  • Hi there!

    I’m facing below error,
    Error Granting permission to Folder! Exception calling “ExecuteQuery” with “0” argument(s): “Server relative urls must start with SPWeb.ServerRelativeUrl”

    Any idea why?

    Reply
    • Most likely you are trying to break the inheritance for a site different than the root site collection.
      try to use the following format for the FolderURL:
      $FolderURL = “/sites///”
      like:
      $FolderURL = “/sites/MyTestSite/MyTestLibrary/MyTestFolder”

      Reply
    • Thanks for the suggestion, my scenario is actually a folder inside a sub-site (not the root site), I tried the ‘/sites///’ format without luck.
      Exception calling “ExecuteQuery” with “0” argument(s): “Server relative urls must start with SPWeb.ServerRelativeUrl”
      It is preventing me from proceeding. Any other ideas?

      Reply
    • Found the fix after two months, removed the ‘/’ from the beginning of the folder name. It became something like this:
      FolderURL=”Documents/test”

      Reply
    • The $SiteURL parameter and Folder’s ServerRelativeURL must be the same web Context!

      Reply
  • Merci beaucoup, damn useful, using it for O365

    Reply

Leave a Reply

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