Create a directory "Table of Contents" with PowerShell

Posted November 2nd @ 1:48 pm by aaron

My friend job (IT at a major pharmaceutical company) has him dealing with tons and tons of documents. He periodically has to burn large directory trees of documents to some media (CD/DVD). He asked me about a way he could easily create an HTML-based “table of contents” (TOC) for the entire burned media - like an index.html file which would live at the root that hyperlinked all the files. My friend is a really smart guy, so I assumed that he actually needed this and it wasn’t a symptom of the real problem. PowerShell is a great candidate for just such a task, and it was a good excuse to get him to install it. It was really fast and easy to write a New-TableOfContents function just by thinking through the problem, almost “out loud” and writing my thoughts in PowerShell-ese.

function New-TableOfContents($path)
{
    # Verify the path exists and retrieve the official full path
    $root = (Get-Item $path).FullName

    Write-Output “<html><head><title>Table of Contents</title></head><body><h1>Table of Contents</h1>”
    # For each child item that’s not a directory, create a link containing the relative path
    Get-ChildItem $root -recurse | where { $_.PSIsContainer -eq $false } |% {
        # Strip the root out of the path name (including the trailing slash)
        # in order to create a hyperlink that can be used from any location
        $relPath = $_.FullName.Remove(0, $root.Length + 1)
        # Write the link out - this is where you could get fancier with what you output
        # For example, you could include the last modified date/time, etc.
        Write-Output “<a href=`”$relPath`“>$relPath</a><br />”
    }
    Write-Output “</body></html>”
}

This function will output the html to the pipeline, which doesn’t do us much good unless you direct it somewhere useful, like a file. While it’s tempting to make a function like this output the results to a file (replace “Write-Output” with “Out-File -append”), I’m of the opinion that functions should return their results to the pipeline whenever possible, allowing the user to decide what to do with it. In this case, it’s as simple as this:

PS:> New-TableOfContents “C:\Doc Tree” | Out-File “C:\Doc Tree\index.html”

It’s simple, but effective. And because PowerShell passes objects around instead of strings, you can easily include more information in the hyperlink, or create a table instead of a list, or sort, or whatever. The sky’s the limit.

1 Trackbacks/Pingbacks

  1. Pingback: Weekly Link Post 14 « Rhonda Tipton’s WebLog on November 4, 2007

Leave a comment

OpenID Login

Standard Login

Options:

Size

Colors