Tuesday, March 08, 2016

How to Inherit Search Navigation in SharePoint with PowerShell

Paul Hermany

We were recently tasked with writing a PowerShell script to inherit search navigation nodes from the root website for all websites in the site collection (on-prem). For the uninitiated, here’s a good overview of how the search dropdown works in SharePoint 2013.

We used a brute force approach (similar to this one) to iterate through all webs, delete all the existing search navigation nodes, and finally copy search navigation from the root.  The initial test was successful, but we noticed that after the script was run more than once, we would end up with duplicate nodes in the search navigation dropdown. Sigh.

Sadly, we fell into the classic “Collection was modified” trap where we were trying to modify a collection during enumeration. A good explanation of the problem and solution in C# can be found here.

Here’s the working version:

# get instance of site collection

$site = Get-SPSite "http://sp13app.local/"



# iterate through all webs

foreach($web in $site.AllWebs) {

  # check that we are not in the root web (only inherit search navigation for subsites)

  if($web.Id -ne $site.RootWeb.Id) {

    # get the number of existing search navigation nodes

    $count = $web.Navigation.SearchNav.Count

    # use a classic for loop to iterate through the collection

    for($i = 0; $i -lt $count; $i++) {

      # delete the 0th node

      $navItem = $web.Navigation.SearchNav[0];

      $node = $web.Navigation.SearchNav.Delete($navItem)

    }



    # iterate through the root navigation nodes

    foreach($navitem in $site.RootWeb.Navigation.SearchNav) {

      # add the node to the search navigation collection

      $node = new-object -TypeName "Microsoft.SharePoint.Navigation.SPNavigationNode" -ArgumentList $navitem.Title, $navitem.Url, $true

      $node = $web.Navigation.SearchNav.AddAsLast($node)

    }

    

    # update the web

    $web.Update()

  }

}

Loading Next Article