Create folders on SharePoint Document Library from CSV

Photo by Maarten van den Heuvel on Unsplash

There are a few options to achieve this result, you can do a PNP template, create a folder individually and that onwards, and there is a command that will create all the folders if you respect some logic which I will use here.

I recommend you update your PNP PowerShell to make sure you got the same cmdlets used by the script. We will use a command that allows us to create a folder if we provide the relative URL of the folders in case those folders do not exist yet. The structure of our CSV is the following, the code will be ready to folderN. Please be aware of some limitations of the lengths on the URL.

The code is below, it will build the required relative URL for the command we’ll use called Resolve-PnPFolder.

$siteUrl = ""
$listName = "FolderTesting"
$folderTemplateCSVPath = "./template.csv"
$folderName = "Folder"

Connect-PnPOnline -Url $siteUrl -UseWebLogin
Write-Host "Connected to site: $siteUrl" 
$csvItems = Import-Csv -Path $folderTemplateCSVPath -Encoding UTF8 

foreach ($item in $csvItems) {
    $folderNumber = 1
    $folderPath = "$listName\"

    While ($($item."$folderName$folderNumber")) {
        $folderPath += ("$($item."$folderName$folderNumber")\")

    $folderPath = $folderPath.Substring(0, $folderPath.Length - 1)
    $folderPath = $folderPath.Replace('//', '/')
    $folder = Resolve-PnPFolder -SiteRelativePath $folderPath 
    Write-Host "Folder created: $folderPath" 

The script will create the folders in a fast way and most of the users will appreciate the fact that you can use CSV to create the folder structure. For more advanced logic you can use the -Include on the Resolve-PnPFolder cmdlet to retrieve the item Id on SharePoint in case you wanna add more functionality to your script.


Be First to Comment

Leave a Reply

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