Create Folders CSOM PowerShell Script Office 365 SharePoint Online

We might have requirements to create folders inside List, Libraries, picture library or any list. We know the process to create folder out of the box for any list which is quite simple. Here I will be sharing code to create folders in lists/libraries using PowerShell which is quite simple.

PS Script –

cls

$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
$xmlFilePath = $(“$dp0\Inputs.xml”)
$xmldata = [xml](Get-Content($xmlFilePath));

$username = “samtest@microsoft.com”
$password = Read-Host -Prompt “Please enter your password” -AsSecureString

$url = $xmldata.WebSite.Url

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-ObjectMicrosoft.SharePoint.Client.SharePointOnlineCredentials($username,$securePassword)
$clientContext.Credentials = $credentials

Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.dll”
Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.Runtime.dll”
Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.Publishing.dll”
Add-Type -Path “C:\Lib\Microsoft.SharePoint.Client.Taxonomy.dll”

if (!$clientContext.ServerObjectIsNull.Value)
{
Write-Host “Connected to SharePoint Online site: ‘$Url'” -ForegroundColorGreen

$web = $clientContext.Web
$clientContext.Load($web)
$clientContext.ExecuteQuery()

}




function CreateFolders([Microsoft.SharePoint.Client.Web] $web)
{
foreach($folderPath in $xmldata.WebSite.Folders.Folder)
{
# Create a new folder
$folder=$web.Folders.Add($folderPath.Path);
$clientContext.Load($folder);
# Execute the query
$clientContext.ExecuteQuery();
Write-Host -ForegroundColor Green “Folder Name: ” $folder.Name ” URL: “$folder.ServerRelativeUrl;
}
Write-Host “Folders Created by Sam”

}

CreateFolders $web

XML Inputs –
<?xml version=”1.0″ encoding=”utf-8″?>
<WebSite Url=”https://microsft.sharepoint.com/sites/test/” >
<Folders>
<Folder Path=”Pages/Folder1″></Folder>
<Folder Path=”Pages/Folder2″></Folder>
<Folder Path=”Lists/ImageLibrary/Folder1″></Folder>
</Folders>
</WebSite>
Happy Scripting.

Read some SharePoint tutorials:


Thanks,
Sambita

Check out Best Alternative to InfoPath -> Try Now

You May Also like the Following SharePoint Online Tutorials:

About Sambita Rath

I have 9 years of exprience into SharePoint implementation, architecture, Administrator, development and Training.Designing Information Architecture in SharePoint 2007, 2010,2013 and Office 365.

View all posts by Sambita Rath →