Create Folder Hierarchies for SharePoint Lists and Libraries using Powershell


A small Powershell snippet which will create folder hierarchies within SharePoint lists and libraries

function EnsureListFolderTree($web, $list, $folderName) {
$curl = $list.RootFolder.ServerRelativeUrl
$folders = $folderName.Replace("^/+","").Split("/")
ForEach($fn in $folders) {
$furl = $curl + "/" + $fn
$f = $web.GetFolder($furl)
if ($f.Exists -eq $false) {
$f = $list.AddItem($curl, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, $fn)
$f.Update()
$f = $web.GetFolder($f.Folder.ServerRelativeUrl)
}
$curl = $f.ServerRelativeUrl
}
$f
}
view raw EnsureListFolderTree hosted with ❤ by GitHub

Usage

$w = Get-SPWeb "http://team.pdogs.local"
$sa = $w.Lists["Site Assets"]

$f = EnsureListFolderTree $w $sa "meetings/q1/q1-1"
$f = EnsureListFolderTree $w $sa "meetings/q1/q1-2"
$f = EnsureListFolderTree $w $sa "meetings/q2/q2-1"
$f = EnsureListFolderTree $w $sa "meetings/q2/q2-2"

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.