Archive

Archive for January, 2012

Powershell as a T4 Text Template alternative

January 18, 2012 1 comment

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)
{
@"
<html>
  <body>
    <h1>$header</h1>
    <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>"
    }
@"
    </table>
  </body>
</html>
"@

}

$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