2013-11-22

When I first heard about Managed Metadata Navigation, I thought all of my navigation dreams had come true.  Alas, it didn’t quite work as expected and the limitation of a single site collection use really had me chapped.  In all of the dark corners of the Internet that I was looking for a solution to this, I didn’t find a good script to make it work like it should have.   So I wrote my own cmdlet.   This script takes a Term Group, Term Set, and Web Application and copies (using pinning), then assigns the copies  to all site collections in the web app.  End result:  Unified Navigation across all sites.

Function Distribute-Navigation()
{
[CmdletBinding()]
param
(
[Parameter(position=1, mandatory=$true, parametersetname="Default")] [string]$TermGroupName, 
[Parameter(position=2, mandatory=$true, parametersetname="Default")] [string]$ParentTermSetName, 
[Parameter(position=3, mandatory=$true, parametersetname="Default")] [string]$WebApplication
)


$WebApp = get-spwebapplication $webapplication
foreach ($site in $webapp.sites) 
{
if ($site.ServerRelativeUrl -ne "/") 
{
$siteName = $site.ServerRelativeUrl.ToString()
$siteName = $sitename.trim("/")
$termGroup = $TermGroupName
$ParentTermSet = $ParentTermSetName
$dstTermSetName = "Global Navigation - " + $siteName + "(LINKED TO MAIN)"
$web = get-spweb $site.url
$session = Get-SPTaxonomySession -site $site 
$store = $session.DefaultKeywordsTermStore
$group = $store.groups[$termgroup]
$srctermset = $group.termsets[$ParentTermSet]
$dstTermSet = $null
$dstTermSet = $group.TermSets | ? {$_.name -eq $dstTermSetName}
if ($dstTermSet -eq $null)
{
write-host "Creating Term Set:"$dstTermSetName
$dsttermset = $group.CreateTermSet($dstTermSetName)
$dsttermset.SetCustomProperty("_Sys_Nav_IsNavigationTermSet", "True")
$dsttermset.CustomSortOrder = $srctermset.CustomSortOrder
} 
else
{
write-host "Term Set Already Exists:"$dstTermSetName
}
foreach ($sourceTerm in $srctermset.terms)
{

$newterm = $null
$newterm = $dsttermset.terms | ? {$_.name -eq $sourceterm.name}
If ($newterm -eq $null)
{
write-host "Adding Term:"$sourceterm.name
$newterm = $dsttermset.reusetermwithpinning($sourceTerm)
}
Else
{
write-host "Term Already Exists:"$sourceterm.name
}
}
$store.CommitAll()
$navSettings = New-Object Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings($web)
$navSettings.GlobalNavigation.Source = 2
$navSettings.GlobalNavigation.TermStoreId = $Store.Id
$navSettings.GlobalNavigation.TermSetId = $dsttermset.Id
$navSettings.AddNewPagesToNavigation = $false
$navSettings.CreateFriendlyUrlsForNewPages = $false
$navSettings.Update()
write-host "Updated Navigation for "$sitename
$web.Dispose()
}
}
}

 

About the author 

Lucas Struck