Home > Uncategorized > Powershell as a T4 Text Template alternative

Powershell as a T4 Text Template alternative

T4 Text templates is a tool for code (or any text really) generation that is built into Visual Studio. A couple of weeks ago I started working on a project that needed a lot of code generation but I could not allow a dependency to Visual Studio so I started writing Powershell scripts instead. I was surprised how nice it turned out to be. Three features of Powershell turns out to be particularly useful:

  • Variable expansions in strings; i.e.  “The variable ‘var’ has value: $var”
  • Here strings (that may contain any characters): @”…”@
  • Multiple returns: { “row1”; “row2”; “row3” } yields an array of the three rows.

(At first when I discovered the multiple returns feature in Powershell I though it was weird and I wondered how it could actually have made it into the language. Now I know better…)

Now, as an example, lets say that we want to generate a html table from a collection of objects and their properties. Using the features above the task can be expressed as:

function ConvertTo-HtmlTable($header, $objects, $properties)
    <table border=`"1`">

    if (!$properties) {
        $properties = Get-Member -InputObject $o -MemberType Properties | select -expandproperty name 
    " <tr>"
    foreach($p in $properties) { " <th>$p</th>" }
    " </tr>"       
    foreach($o in $objects) 
        " <tr>"
        foreach($p in $properties)
            $value = Invoke-Expression ("`$o." + $p)
            " <td>$value</td>"
        " </tr>"


$objects = Get-Process
ConvertTo-HtmlTable `
"Process information" $objects Id, Name, PrivateMemorySize | Out-File "page.html"

Sometimes  I think generating code written in Powershell even outshines a corresponding T4 templates implementation. Nice!

Categories: Uncategorized
  1. November 8, 2012 at 4:26 am

    I know it’s been a while, but I also found a powershell to great for templating, especially once get into using the Razor view engine. At that point it’s pretty perfect. 😀


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: