T4 template to Generate PowerShell Script

The following T4 template generates the PowerShell script in page Use PowerShell with SharePoint Object Model.

<#@ import namespace="System.Text" #>
<#@ template inherits="Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation" #>
<#@ output extension=".ps1" #>
<#@ SharePointTopNavDSL processor="SharePointTopNavDSLDirectiveProcessor" requires="fileName='Sample.topnav'" #>
[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");

$url = "<#=this.TopNav.SiteUrl#>"
$topsite = new-object Microsoft.SharePoint.SPSite $url;
$topweb = $topsite.OpenWeb()
$topnavs = $topweb.Navigation.TopNavigationBar

$node0 = $topnavs[0]
while ($node0.Children.Count -gt 0) { $node0.Children.Delete($node0.Children[0])}

<#
foreach (Link link in this.TopNav.Links)
{
if(link.Parent==null)
{
#>
<#= ProcessLink(0, link) #>
<#
}
}
#>

<#+
public string ProcessLink(int level, Link link)
{
string parentNode = "$node" + level ++;
string thisNode = "$node" + level;
StringBuilder sb = new StringBuilder();

sb.AppendFormat("{0} = new-object Microsoft.SharePoint.Navigation.SPNavigationNode -argumentlist @(\"{1}\", \"{2}\", ${3})\r\n",
thisNode, link.Title, link.Url, link.IsExternal);
sb.AppendFormat("{0} = {1}.Children.AddAsLast({0})\r\n", thisNode, parentNode);

if(link.Items!=null && link.Items.Count>0)
{
foreach(Link l in link.Items)
{
sb.Append(ProcessLink(level, l));
}
}
return sb.ToString();
}
#>

This template is based on the top navigation DSL model. It translates the links within the model into a runnable PowerShell script. Problem of this template is that it relys on links' sequence in the model, not the display order (y-coordinate).

If you want to discuss on this problem, please visit development related questions and give your have comments.

Last edited Feb 26, 2008 at 8:28 PM by yysun, version 6

Comments

No comments yet.