Friday, March 01, 2013

PowerShell / SharePoint - Make sure a folder path exists

I recently needed to write a script to copy a set of files and folders to a SharePoint site. Copying the files was pretty easy, but making sure that a path existed and creating any missing folders ended up being harder than needed. Here is a function that will make sure a path exists, creating any missing folders.


<#
  $web = Get-SPWeb "http://eddevjc/site"
  $relativeUrl = $web.ServerRelativeUrl
  $path = "test1/test2/test3"
  $folders = $path.Split("/")
  AddSPFolder $web $relativeUrl $folders
#>

function AddSPFolder ($web, $relativeUrl, $folders)
{
    # grab the first folder to check
    $first, $rest = $folders
    # join to the relative url and check for existence
    $folder = $web.GetFolder( ($relativeUrl,$first -join "/") )
    if (-not $folder.Exists)
    {
        Write-Output "AddSPFolder $first to $relativeUrl "
        # get parent folder and create new folder
        $web.Getfolder($relativeUrl).SubFolders.Add($first)
    }
    if ($rest.Length -gt 0)
    {
        AddSPFolder $web ($relativeUrl, $first -join "/") $rest
    }
}

One other thing, if you have PowerShell ver 3, you will have to run it as ver 2 because the SharePoint PowerShell snap-in only works under ver 2. Just run this before runing the script:

powershell -version 2.0


1 comment:

Anonymous said...

This is exactly what I am needing. I'm using SharePoint 2010 and when I run this script from the SharePoint 2010 Management Shell (as admin) I'm getting this error:

The term 'AddSPFolder' is not recognized as teh name of a cmdlet, function, script file, or operable program.

Thanks for any help.

Post a Comment