Office 365 - Creating a Subsite (Web) using CSOM in SharePoint Online

SharePoint Online has a number of PowerShell Cmdlets -, these Cmdlets include New-SPOSite which provides the ability to create a Site Collection, unfortunately it's not possible to create a SubSite (web) using these Cmdlets - it is however possible to use CSOM to do this and the script below demonstrates how to create a SubSite and a site beneath the SubSite (a SubSubSite?).

The script below is broken into three sections, the first section is used to connect to the SharePoint Online Site that you wish to create the Subsite within, simply update the highlighted $Site variable with the relevant URL.

The second section creates a SubSite within the Site Collection. Update the highlighted variables to match your requirements, I've used the Team Site template (STS#0) in this example.

The third section creates a Site beneath the SubSite that was just created, again update the highlighted variables to meet your requirements. The key thing to note when creating a SubSite beneath an existing SubSite is that you must include the relative path to the new SubSite within the $WCI.Url variable. In this case I first created a SubSite with the URL to create a SubSite beneath this I must specify the relative path of the SubSubSite to create therefore /SubSite/SubSubSite.

#Add references to SharePoint client assemblies and authenticate to Office 365 site
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Publishing.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$Username = Read-Host -Prompt "Please enter your username"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Site = ""
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($Site)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username,$Password)
$Context.Credentials = $Creds

#Create SubSite
$WCI = New-Object Microsoft.SharePoint.Client.WebCreationInformation
$WCI.WebTemplate = "STS#0"
$WCI.Description = "SubSite"
$WCI.Title = "SubSite"
$WCI.Url = "SubSite"
$WCI.Language = "1033"
$SubWeb = $Context.Web.Webs.Add($WCI)

#Create SubSubSite
$WCI = New-Object Microsoft.SharePoint.Client.WebCreationInformation
$WCI.WebTemplate = "STS#0"
$WCI.Description = "SubSubSite"
$WCI.Title = "SubSubSite"
$WCI.Url = "SubSite/SubSubSite"
$WCI.Language = "1033"
$SubWeb = $Context.Web.Webs.Add($WCI)

Brendan Griffin - @brendankarl

Steve Jeffery - @moss_sjeffery