Effortless month-based folder creation in SharePoint Online

Hello there! Today’s post will help you create a folder structure in SharePoint Online organized by month’s name!

You’ll see that with just a few lines of PowerShell, your folders will be created in seconds without hard-coding the names 😏

Create a script

As we have only a few lines of code, we can go down the route of creating a very small PowerShell script. Here it is:

#Connect to a SPO Site
Connect-PnPOnline -Url "https://<YOUR-TENANT-NAME>.sharepoint.com/sites/<YOUR-SITE>"

#Targeted document library
$myList = "<YOUR LIBRARY>"

#Create the folders
for($i = 1; $i -le 12; $i++){
    Add-PnPFolder -Name (Get-Culture).DateTimeFormat.GetMonthName($i) -Folder $myList
}

Or create a Function…

function New-FolderPerMonth {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Site Url to connect to", Position = 0)] 
        [string]$SiteUrl,  
        [Parameter(Mandatory = $true, HelpMessage = "List to create the folders in", Position = 1)] 
        [string]$LibraryName  
    )
    #Connect to the designated site
    Connect-PnPOnline -Url $SiteUrl
    
    #Create the folders
    for ($i = 1; $i -le 12; $i++) {
        Add-PnPFolder -Name (Get-Culture).DateTimeFormat.GetMonthName($i) -Folder $LibraryName
    }
}

New-FolderPerMonth -SiteUrl "https://<YOUR-TENANT-NAME>.sharepoint.com/sites/<YOUR-SITE>" -LibraryName "<YOUR-LIBRARY-NAME>"

For this script, we need to change tactic. The reason being that above, we use the For loop, with a variable $i which is a number.

Now, we’d need this $i to be a string. So if we keep it as it is, we’ll run into an error that $i++ cannot be converted to a string!

Therefore, we’re going to use the foreach loop, and format the numbers 1,2,3… to 01, 02, 03… Otherwise, we’ll face the same problem whereas our folders won’t be in order 🙂

Function with numbers

function New-FolderPerMonthWithNumber {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, HelpMessage = "Site Url to connect to", Position = 0)] 
        [string]$SiteUrl,  
        [Parameter(Mandatory = $true, HelpMessage = "List to create the folders in", Position = 1)] 
        [string]$Library 
    )
    #Connect to the designated site
    Connect-PnPOnline -Url $SiteUrl
    
    #Create the folders
    foreach ($monthsNumber in @(1..12)) {
        
        $monthNumFormatted = "{0:d2}" -f $monthsNumber
        Add-PnPFolder -Name ($monthNumFormatted + "_" + (Get-Culture).DateTimeFormat.GetMonthName($monthNumFormatted)) -Folder $Library
    }
}

New-FolderPerMonthWithNumber -SiteUrl "https://<TENANT-NAME>.sharepoint.com/sites/<YOUR-SITE>" -Library "<YOUR-LIBRARY-NAME>"

Thanks for reading! 🙂

Discover more from Veronique's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading