Create Library and Nested Folder Structure in SharePoint Using PnP PowerShell

Learn to create Library and nested folder structure in SharePoint using PnP PowerShell.

Overview
 
I am going to show how to create a Library and Folder structure using PnP PowerShell.
 
Below is the folder structure.
 
 
 
One way to create folders is manual but it is a time-consuming process and error-prone. Another method is to create folders using PowerShell.
 
Pre-requisites
  • PowerShell installed on your machine.
  • PnP package installed and updated.
Below is the code
  1. $Url =Read-host "enter url"
  2. $filePath="Path/name.csv"
  3. # Reads the csv file and gets all records in one collection
  4. $rowCollection = import-csv $filePath
  5. $libName="Library name"
  6. $libDisplayName="Display name for library"
  7. ########################################################## Create Folders in Library ######################################
  8. function CreateFolders()
  9. {
  10. Connect-PnPOnline -Url $Url -Credentials(Get-Credential)
  11. Write-Host "Site Connected"
  12. Remove-PnPList -Identity FSCAudit
  13. New-PnPList -Title $libDisplayName -Url $libName -Template DocumentLibrary -OnQuickLaunch
  14. Write-Host "Library created"
  15. foreach ($myRow in $rowCollection) {
  16. try {
  17. if(![string]::IsNullOrEmpty($myRow.'Folder')){
  18. Add-PnPFolder -Name $myRow.Folder -Folder $libName
  19. Write-Host "Folder created - " $myRow.Folder
  20. $pathSemiFolder=$libName+"\"+$myRow.Folder
  21. if(![string]::IsNullOrEmpty($myRow.'SemiFolder'))
  22. {
  23. $option = [System.StringSplitOptions]::RemoveEmptyEntries
  24. $($myRow.SemiFolder.split(',',$option)).foreach{
  25. Add-PnPFolder -Name $_ -Folder $pathSemiFolder
  26. Write-Host "Folder created - " $_
  27. }
  28. }
  29. else {
  30. Write-Host "Sub folders does not exist"
  31. }
  32. }
  33. else {
  34. Write-Host "Folder name is empty"
  35. }
  36. }
  37. catch {
  38. Write-Error -Message $Error[0].Exception.Message -ErrorAction Continue
  39. }
  40. }
  41. }
  42. #################################################################################################################
  43. CreateFolders
Run script using PowerShell Command prompt.
 
Once the script is completed, you can see the Library and the folder structure in SharePoint.
 
This is helpful if you get frequent requests for creating a nested Folder structure.