Quantcast
Channel: Cloud Design Box – Tony Phillips
Viewing all articles
Browse latest Browse all 66

Deleting all navigation nodes using CSOM PowerShell

$
0
0

It’s fairly straightforward to enumerate nodes in an array, in this example I’m deleting all the top navigation menu nodes in a SharePoint site. This is how I would normally loop through the top navigation menu:

$topNav = $context.Web.Navigation.TopNavigationBar;
$context.Load($topNav);
foreach ($topNavItem in $topNav)
{
	Write-Host $topNavItem.Title
}

However if I want to loop through the menu and delete all the nodes, the above function errors as the array has changed each time it loops, the method below works but doesn’t catch all the menu items.

for ($ii = 0; $ii -lt $topNodes.Count; $ii++)
{
	Write-Host $topNodes[$ii].Title 
	$topNodes[$ii].deleteObject();
	$context.ExecuteQuery();
}

As we are enumerating the nodes, we are removing nodes from the start and changing the position of the other nodes in the array. As the loop continues to run, it can skip positions of some of the nodes.

A solution which works better is looping through the array backwards. As you loop through the array backwards, it doesn’t change the position of items still in the array.

for ($ii = $topNodes.Count - 1; $ii -ge 0; $ii--)
{
	Write-Host $topNodes[$ii].Title 
	$topNodes[$ii].deleteObject();
	$context.ExecuteQuery();
}

Hope you may find this useful, it can be difficult to find why the loop misses some random items and hopefully looping backwards will avoid any issues like this.


Viewing all articles
Browse latest Browse all 66

Trending Articles