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
- $Url =Read-host "enter url"
- $filePath="Path/name.csv"
- # Reads the csv file and gets all records in one collection
- $rowCollection = import-csv $filePath
- $libName="Library name"
- $libDisplayName="Display name for library"
-
- ########################################################## Create Folders in Library ######################################
-
- function CreateFolders()
- {
- Connect-PnPOnline -Url $Url -Credentials(Get-Credential)
- Write-Host "Site Connected"
- Remove-PnPList -Identity FSCAudit
- New-PnPList -Title $libDisplayName -Url $libName -Template DocumentLibrary -OnQuickLaunch
- Write-Host "Library created"
- foreach ($myRow in $rowCollection) {
- try {
- if(![string]::IsNullOrEmpty($myRow.'Folder')){
- Add-PnPFolder -Name $myRow.Folder -Folder $libName
- Write-Host "Folder created - " $myRow.Folder
- $pathSemiFolder=$libName+"\"+$myRow.Folder
- if(![string]::IsNullOrEmpty($myRow.'SemiFolder'))
- {
- $option = [System.StringSplitOptions]::RemoveEmptyEntries
- $($myRow.SemiFolder.split(',',$option)).foreach{
- Add-PnPFolder -Name $_ -Folder $pathSemiFolder
- Write-Host "Folder created - " $_
- }
- }
- else {
- Write-Host "Sub folders does not exist"
- }
-
- }
- else {
- Write-Host "Folder name is empty"
- }
-
- }
-
- catch {
- Write-Error -Message $Error[0].Exception.Message -ErrorAction Continue
- }
-
-
- }
-
- }
-
-
- #################################################################################################################
-
- 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.