SharePoint 2013: PowerShell to Create a Folder in Document Library

Requirement: Create a new folder in SharePoint

How to add a folder in SharePoint Document Library using PowerShell?

To create a folder in the document library in SharePoint 2013, use this PowerShell script:

$folder = $list.Folders.Add("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "New")
$folder.Update()

The above codes doesn’t provide much fault tolerance, isn’t it?

  • What if the particular library we are looking for doesn’t exists?
  • What if the folder we are trying to add already exists on the library?

Error! So lets re-write the code in PowerShell with little fault tolerance!

create folder in sharepoint document library powershell

How to Create Folders and Sub-Folders in SharePoint List using PowerShell?

Here is the PowerShell code snippet for creating Folders and Sub-Folders inside SharePoint List or Library:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Get the Web
$web=Get-SPWeb "http://sharepoint.company.com"
#Get the List/Library
$list=$web.Lists.TryGetList("SalesList")

If($list)  #Check If List exists!
{
    #Check Folder Doesn't exists in the Library!
    $folder = $list.ParentWeb.GetFolder($list.RootFolder.Url + "/" +"Sales List");
    #sharepoint powershell check if folder exists
    If($folder.Exists -eq $false)
    {
       #Create a Folder
       $folder = $list.AddItem([string]::Empty, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "Sales Sub-Item")
       $folder.Update();
    }
   
    #Create a Sub-Folder "APAC Sales Documents" inside "Sales Documents"    
    $Subfolder = $list.ParentWeb.GetFolder($folder.URL + "/" + "APAC Sales Documents");
    
    #Check if sub-folder doesn't exist already
    If ($Subfolder.Exists -eq $false)
    {
       #Create a Sub-Folder Inside "Sales Documents"
       $Subfolder = $list.AddItem($folder.URL, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "APAC Sales Documents")
       $Subfolder.Update();
    }
}

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

5 thoughts on “SharePoint 2013: PowerShell to Create a Folder in Document Library

  • December 11, 2020 at 10:23 AM

    how to pass the folder name in a variable

    Reply
  • December 11, 2020 at 10:23 AM

    how to pass the folder name in a variable

    Reply
  • August 16, 2017 at 10:39 PM

    Error when attempting to create the folder:”Invalid Yes/No value.
    A Yes/No field contains invalid data. It should be either 1 or 0. Please check the value and try again.”

    Could you please help me?

    Reply
  • July 6, 2017 at 4:17 PM

    saved ton of time . Thank you 🙂

    Reply

Leave a Reply