Create A Folder And Set Unique Permission Using PnP PowerShell

Introduction

 
In this blog, we are going to create a folder in Document Library and set unique permission to a user for this created folder using PnP Power Shell. The Administrator can set the required permission to a user depending on the organizational needs. Here we can use this script to set permission to a particular user. Please follow the below steps.
 
Step 1
 
Run the ISE in administrative mode. Then declare variables named “sUrl”, “user”, “Folder Name”, and “SiteRelativeURL” to store the respective values.
 
Step 2
 
Connect to PnP online and get the credentials.
 
Connect-PnPOnline-Url$sUrl-Credentials (Get-Credential)
 
Step 3
 
To create the folder in the document, use the PnP commands as shown in the code.
 
Add-PnPFolder-Name$FolderName-Folder$SiteRelativeURL-ErrorActionStop
 
Step 4
 
Copy and run the below codes to create a folder in Document and to set unique permission in the folder for a user.
  1. #Config Variables  
  2. $sUrl = "https://contoso.sharepoint.com/sites/scriptEnable"  
  3. $user = "srikanta@contoso.onmicrosoft.com"  
  4. $FolderName = "Team Projects"  
  5. $SiteRelativeURL = "/Shared Documents"  
  6. #Site Relative URL in which the folder will be created  
  7. Try {  
  8.     Connect - PnPOnline - Url $sUrl - Credentials(Get - Credential)  
  9.     # create folder using powershell  
  10.     Add - PnPFolder - Name $FolderName - Folder $SiteRelativeURL - ErrorAction Stop  
  11.     Write - host - f Green "New Folder '$FolderName' Created Sucessfully!"  
  12. catch {  
  13.     write - host "Error: $($_.Exception.Message)" - foregroundcolor Red  
  14. }  
  15. try {  
  16.     Write - host - f Green "Adding unique permission to '$FolderName'"  
  17.     $Path = "/sites/scriptEnable/Shared%20Documents/" + $FolderName  
  18.     #Set folder permissions  
  19.     Set - PnPfolderPermission - List $ListName - identity $Path - User $user - AddRole "Edit"  
  20.     Write - host "Successfully added permission" - ForegroundColor Green  
  21. catch {  
  22.     write - host "Error: $($_.Exception.Message)" - foregroundcolor Red  
  23. }   
After running the script,
 
Create A Folder And Set Unique Permission Using PnP PowerShell
 
Folder “Team Project” is created successfully.
 
Create A Folder And Set Unique Permission Using PnP PowerShell
 
Now the permission is updated,
 
Create A Folder And Set Unique Permission Using PnP PowerShell