powershell function to create html table of contents

I recently swapped from self-hosted WordPress to wordpress.com.

While wordpress.com is very, very good I couldn’t find a way of creating a Table of Contents. I used to do this with a WordPress plugin.

Anyway, this is still very much a work in progress, but I knocked up some Powershell code to read and html file, then write the html file with a TOC at the top.

The most recent version of this will be on Github but my current version is below.

function add-TocToHtml {
Reads in an html page, writes out an html page with a table of contents

Todo: parameterize what headings are toc-ed
Todo: make it work with headings other than


Todo: indent the toc depending on the heading level
Todo: create the toc with a specified font size
Todo: add-in a go back to the top link before each heading, optionally
Todo: some error-handling would be both nice and novel

File containing the html to which you want to add a TOC

File to which to write the TOC-ed html
Enter the word 'Screen' to have it output to the screen, or pipeline

Example of how to use this cmdlet

Another example of how to use this cmdlet
Param( [string][Alias ("i")]$InputFile = "c:\temp\post.html",
[string][Alias ("o")]$OutputFile = "c:\temp\post_with_Toc.html")

write-debug "$(get-date -format 'hh:mm:ss.ffff') Function beg: $([string]$MyInvocation.Line) "

write-debug "$InputFile: $InputFile"
write-debug "
$OutputFile: $OutputFile"

$InputText = get-content $InputFile

$OutputText = ""
$TocText = ""

foreach ($Line in $InputText)
if ($Line -like "h3")
$Title = $Line.Split("")[2]
write-debug "`$Title: $Title"

  $Anchor = $Title.replace(" ", "")
  write-debug "`$Anchor: $Anchor"

  $OutputLine = "`n`n<h3>$Title</h3><br>`n"
  write-debug "`$OutputLine: $OutputLine"

  $OutputText = $OutputText + $OutputLine

  $TocLine = "<a>$Title</a><br>`n"
  write-debug "`$TocLine: $TocLine"

  $TocText = $TocText + $TocLine
  if ($Line -ne "")
    $OutputText = $OutputText + $Line + "<br>`n"


if ($OutputFile -ne "Screen")
$TocText | out-file $OutputFile
$OutputText | out-file -append $OutputFile

write-debug "$(get-date -format 'hh:mm:ss.ffff') Function end: $([string]$MyInvocation.Line) "


set-alias atth add-TocToHtml