Create folder in a SharePoint Online list using PowerShell

There are many examples on how to create folders using PowerShell in SharePoint Online document libraries. At least at the time of writing, there’s no guidance on how to programatically create folders in SharePoint lists. It may not be a common scenario but here’s the script if you have a need to do so:

cls

#Since the time I wrote the original script (all the way to the bottom),
# I found out that you can achieve this using 
# the Add-PnPFolder command. I have therefore commented out
# the earlier script I wrote towards the bottom. Thanks!

#region declarations
$siteUrl = "https://tenant.sharepoint.com/sites/StarkEnterprises"
$folderName="Mark VIII"

#Note that the command expects the list "url name" instead of the display title
# Also note that the url name not be encoded 
# so use "Lists/Awesome Suites" instead of "Lists/Awesome%20Suites"
$parentFolderRelativeURL = "Lists/Awesome Suites"

#The following would create a subfolder under the "Mark I to X" folder instead of the root
#$parentServerRelativeUrl= "Lists/Awesome Suites/Mark I to X" 

#endregion

#Add folder to list
Add-PnPFolder -Name $folderName -Folder $parentFolderRelativeURL

<#
#region declarations
$siteUrl = "https://tenant.sharepoint.com/sites/StarkEnterprises"
$listTitle = "Suites"
$folderName="Mark VIII"
$parentServerRelativeUrl= "/sites/StarkEnterprises/Lists/Suites" #create folder at the root of the list

#The following would create a subfolder under the "Mark I to X" folder instead of the root
#$parentServerRelativeUrl= "/sites/StarkEnterprises/Lists/Suites/Mark I to X" 

#endregion

#region connect to the site and get the list object
Connect-PnpOnline -Url $siteUrl -Interactive
$ctx = Get-PnPContext

$list = $ctx.web.Lists.GetByTitle($listTitle)
$ctx.Load($list)
$ctx.ExecuteQuery()
#endregion

#region create the ListItemCreationInfo object
$listItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$listItemInfo.FolderUrl = $parentServerRelativeUrl
$listItemInfo.LeafName=$folderName
$listItemInfo.UnderlyingObjectType = [Microsoft.SharePoint.Client.FileSystemObjectType]::Folder
#endregion

#region create the folder using the listItemInfo
$listItem = $list.AddItem($listItemInfo)
$listItem["Title"] =$folderName
$listItem.Update()
$Ctx.ExecuteQuery()
#endregion
#>

The prerequisites for the script are:

  1. You will need to have the PnP PowerShell module installed
  2. You will need to have enabled Folder creation for lists via your list settings page
  3. You will of course need to have contribute or higher permissions to the list or folder underneath which you’d like to create the new folder

That’s it. Hope this helps someone!

Related: https://gauravmahajan.net/2023/10/04/move-list-item-to-a-folder-in-sharepoint-online-using-powershell/

This entry was posted in Uncategorized and tagged , , , , , , , . Bookmark the permalink.

Leave a comment