Below is a script that can get a SharePoint online root site and subsites. How do I get 2 , 3 and 4th level of subsites? For example:
- https://test1.ad.com
- https://test1.ad.com/site1
- https://test1.ad.com/site1/subsite1
- https://test1.ad.com/site1/subsite1/subsubsite1
- and so on
Generate ClientContext function so we can reuse
function GetClientContext($SiteCollectionUrl, $username, $password)
{
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollectionUrl)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$context.Credentials = $credentials
return $context
}
Function to loop through subsites
function catchsubsites ($subsiteurl)
{
$clientContext = GetClientContext $subsiteurl $username $password
$rootWeb = $clientContext.Web
$childWebs = $rootWeb.Webs
$clientContext.Load($rootWeb)
$clientContext.Load($childWebs)
$clientContext.ExecuteQuery()
#do something on top level site
write-host $rootWeb.url -ForegroundColor Yellow
foreach ($childWeb in $childWebs)
{
#do something for each subsite
write-host $childWeb.url -ForegroundColor Yellow
#see if there are any subsites beneath this and loop all of them too
#catchsubsites $childWeb.url
}
}
Finally run the function to get it all started!
catchsubsites $SiteCollectionUrl