Tuesday, October 20, 2015

PowerShell: SharePoint 2010 Add top/Global navigation links and sublinks

This works for SharePoint 2010 sites with the Publishing feature enabled.
Before getting started, populate the header, title and URLs in an XML file (I am saving this in a file called topNav.xml).

Sample format:

 <Navigation>  
      <Group Title="Sites">  
           <Link>  
                <Name>Asia Pacific</Name>  
                <Url>http://asiapac</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Canada</Name>  
                <Url>http://canada</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Europe</Name>  
                <Url>http://eu</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Japan</Name>  
                <Url>http://japan</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>Penang</Name>  
                <Url>http://penang</Url>  
                <Target />  
           </Link>  
           <Link>  
                <Name>United States</Name>  
                <Url>http://states</Url>  
                <Target />  
           </Link>  
      </Group>  
 </Navigation>  

And here is the powerShell script to grab the values and populate the Global Navigation section.



 $webName = "http://sharepoint/test/"  
 $RemoveSnapInWhenDone = $False  
 if (-not (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue))  
 {  
   Add-PSSnapin Microsoft.SharePoint.PowerShell  
   $RemoveSnapInWhenDone = $True  
 }  
 $web = Get-SPWeb $webName  
 $CreateNavigationNodeMethod = [Microsoft.SharePoint.Publishing.Navigation.SPNavigationSiteMapNode]::CreateSPNavigationNode  
 [xml]$inputXml = Get-Content D:\PowerShell\topNav.xml  
 foreach ($group in $inputXml.Navigation.Group)  
 {  
      $Heading = $group.getAttribute("Title")  
      write-host $Heading -foregroundcolor yellow  
      $headingNode = $CreateNavigationNodeMethod.Invoke($Heading, [System.String]::Empty, [Microsoft.SharePoint.Publishing.NodeTypes]::Heading, $web.Navigation.TopNavigationBar)  
     $headingCollection = $headingNode.Children  
      foreach ($link in $group.ChildNodes)  
      {  
              Write-Host "Creating Sub-Link: $($link.Name)"  
           #Method 2  
          $linkNode = $CreateNavigationNodeMethod.Invoke($link.Name, $link.Url, [Microsoft.SharePoint.Publishing.NodeTypes]::AuthoredLinkPlain, $headingCollection)  
            $linkNode.Update()  
      }  
 }  
 $web.Update()  
 $web.Dispose()  

No comments:

Related Posts Plugin for WordPress, Blogger...