Trying to create multiple things in PowerShell with CSOM for SharePoint Online:
- Create a project (subsite) in the site collection (root)
- Create a level (subsite) underneath the project subsite (so basically a subsite under an existing subsite).
I used this code to create a subsite in the root:
#Specify tenant admin and site URL
$Username = "[email protected]"
$Password = Read-Host -Prompt "Please enter your password" -AsSecureString
$Site = "https://contoso.sharepoint.com/sites/projects"
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($Site)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username,$Password)
$Context.Credentials = $Creds
#Search Subsite Templates
#$Templates = $Context.Site.GetWebTemplates("1043","0")
#$Context.Load($Templates)
#$Context.ExecuteQuery()
#$Templates | Where {$_.Name -like "*STS#0*" } | Select Name, Description
#Main / project
#Load CSV
$dataSource = import-csv “C:\temp\contoso.csv”
foreach($dataRecord in $dataSource)
{
#Define properties
$projectnummer = $dataRecord.Projectnummer
$project = $dataRecord.Project
#check if subsite is present or not
$web = $Context.Web
$Context.Load($web.Webs)
$Context.ExecuteQuery()
$subweb = $web.Webs | where{$_.Url -like "*$projectnummer*"}
if($subweb)
{
#Execute if subsite exists
Write-Host "Project $projectnummer exists" -ForegroundColor Green
continue
}
else
{
#Execute if subsite does not exists
Write-Host "Project $projectnummer does not exists yet, creating..." -ForegroundColor Green
#Create Subsite in root
$Subsite = New-Object Microsoft.SharePoint.Client.WebCreationInformation
$Subsite.WebTemplate = "STS#0"
$Subsite.Title = "$project"
$Subsite.Description = "$projectnummer"
$Subsite.Url = $projectnummer
$Subsite.Language = "1043"
$SubWeb = $Context.Web.Webs.Add($Subsite)
$Context.Load($SubWeb)
$Context.ExecuteQuery()
}
}
This is working, but now I want to create a subsite in the subsite that is just created, but how? I changed the $site
value with this, but that did not work:
$Site = $Site + "/" + $projectnummer + "/"
In that subsite, I also need to create multiple document libraries, but I think I can do that as long as I can create the correct subsite at the right location.