SharePoint Online: PowerShell to Bulk Create Folders in a Document Library from a CSV File

Requirement: Create Multiple Folders in a Document Library from a CSV File in SharePoint Online.

PowerShell to Bulk Create Folders from a CSV File in SharePoint Online:
I got to create a bunch of folders in a SharePoint Online document library! This PowerShell script takes folder names from a CSV file and creates folders in specified document library.
#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/Ops"
$CSVFilePath = "C:\Temp\Folders.csv"
$LibraryName = "Documents"

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -UseWebLogin
    $Web = Get-PnPWeb

    #Get the Document Library and its site relative URL
    $Library = Get-PnPList -Identity $LibraryName -Includes RootFolder
    $LibrarySiteRelativeURL = $Library.RootFolder.ServerRelativeUrl.Replace($Web.ServerRelativeUrl,'')

    #Get the CSV file
    $CSVFile = Import-Csv $CSVFilePath
 
    #Read CSV file and create document document library
    ForEach($Row in $CSVFile)
    {
        #Replace Invalid Characters from Folder Name, If any
        $FolderName = $Row.FolderName
        $FolderName = [RegEx]::Replace($FolderName, "[{0}]" -f ([RegEx]::Escape([String]'\"*:<>?/\|')), '_')

        #Frame the Folder Name
        $FolderURL = $LibrarySiteRelativeURL+"/"+$FolderName

        #Create Folder if it doesn't exist
        Resolve-PnPFolder -SiteRelativePath $FolderURL | Out-Null
        Write-host "Ensured Folder:"$FolderName -f Green
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
Here is my CSV File format:
powershell to create multiple folders in sharepoint online document library from CSV file

You can download it here: CSV File to Create Multiple Folders in SharePoint Online

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.