SCENARIO

You’ve got a create a folder structure in a SharePoint Online Document Library where each folder has the same subfolders. Something that looks like this:

  • FOLDER 1
    • SUB FOLDER 1
    • SUB FOLDER 2
  • FOLDER 2
    • SUB FOLDER 1
    • SUB FOLDER 2

Doing this for a small number, a relatively simple manual process, but if the ask is for a large number then PnP.PowerShell is the way forward.

POWERSHELL

For this example I’m using PnP.PowerShell 2.12.0 and PowerShell 7 executed through Visual Studio Code. You will also need site collection administrator access on the site itself.

The example also uses a string array for the folder names, but you could easily replace that with a csv input for the same result.

Import-Module PnP.PowerShell
#Connect to site.
#Replace with your site url, connection client ID for PnP, and library name
$siteUrl = "https://yoursite.sharepoint.com/sites/thesite"
$clientID = "yourclientIDGUID"
$libraryName = "LibraryName"
Connect-PnPOnline -Url $siteUrl -Interactive -ClientId $clientID

#Define the array of highest level of folders
$folderNames = @(
    "FOLDER 1",
    "FOLDER 2"
)

#Define the array of subfolders
$subFolders = @(
    "SUB FOLDER 1",
    "SUB FOLDER 2"
)

#Function for checking a folder exists and creating if required
function CheckFolder {
    param (
        [string]$folderName,
        [string]$folderPath
    )
    $folder = Get-PnPFolder -Url "$folderpath/$folderName" -ErrorAction SilentlyContinue
    #If it doesn't exist
    if (-not $folder)
    {
        write-host "Creating folder: $folderName"
        Add-PnPFolder -Name $folderName -Folder $folderPath -ErrorAction Stop
    }
    else
    {
        write-host "Folder already exists: $folderName"
    }
}

#Loop through $folderNames and create the folder structure
foreach ($folderName in $folderNames)
{    
    CheckFolder -folderName $folderName -folderPath $libraryName
    #Loop through $subFolders and create the folder structure
    foreach ($subFolder in $subFolders)
    {
        $newPath = "$libraryName/$folderName"
        CheckFolder -folderName $subFolder -folderPath $newPath
    }
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply