I'm using PowerShell ISE and SharePointPnPPowerShellOnline to get the TopNavigationBar navigation nodes from a hub site. I want all nodes in all levels. The navigation is 3 levels as you can see on the picture:
My code is able to get 2 levels if I comment out the last if check etc, but not the 3 level nodes, and I get an error message.
An error occurred while enumerating through a collection: The collection has not been initialized.
It has not been requested or the request has not been executed. It may need to be explicitly requested..
At C:\Users\some.name\scripts\getNavigationps1:24 char:15
+ ... $subChild = $child.Children | Select Title, Url, Id
+ CategoryInfo : InvalidOperation: (Microsoft.Share...NavigationNode]:<GetEnumerator>d__0) [], RuntimeException
+ FullyQualifiedErrorId : BadEnumeration
The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
getNavigation-Ingrid.ps1:26 char:23 foreach($subChild in $child.Children)
Is there something wrong in my logic/"code"?
Connect-PnPOnline -Url "https://xxxxxx.sharepoint.com/sites/testhub2"
$TopNavs = Get-PnPNavigationNode -Location TopNavigationBar |Select Title,Url, Id
foreach($TopNav in $TopNavs)
{
$node = Get-PnPNavigationNode -Id $TopNav.Id
Write-Host
Write-Host "TopNav_Id: [" $TopNav.Id "]" "Title: " $TopNav.Title "Url: " $TopNav.Url
Write-Host
if($node.Children)
{
$child = $node.Children | Select Title, Url, Id #gets topnavs children
foreach($child in $node.Children){
Write-Host " ++ child_Id: [[ " $child.Id"]]" "Title: " $child.Title "Url: " $child.Url
Write-Host
if($child.Children)
{
$subChild = $child.Children | Select Title, Url, Id #gets childrens children
foreach($subChild in $child.Children)
{
Write-Host " ++ subChild_Id: " $subChild.Id "Title: " $subChild.Title "Url: " $subChild.Url
}
}
}
}
}
Appreciate any thoughts and answers!