Updated PowerShell TreeForm

Not too long ago I wrote a blog post about a Windows Form PowerShell script to display a folder tree. I got some feedback about an error when running the script. The problem was that I was casting a variable in one of the functions to a specific type. Normally this is considered a best practice. But in this situation the [System.Windows.Forms.TreeNode] class depends on the parent class being loaded in your PowerShell session. Even though I thought I had tested thoroughly on PowerShell v1 and v2 I must have missed something and the [System.WIndows.Forms] class was getting loaded into my shell prior to running the script, which is why I never saw the error.  Anyway, I’ve since modified the problematic function to remove the type casting. Since I can trust that a treenode is getting passed to the function I can live without.

While I was at it, I also added a debug feature.  Throughout the script I’ve added numerous Write-Debug expressions so I can follow what the script is doing at any given time. If you use -debug as a parameter, the Debug pipeline is enabled by setting the $debugPreference to Continue.

Param ([string]$path=$env:temp,[switch]$debug)
 
if ($debug) {
  $debugPreference="Continue"
 }
 
Write-Debug "Starting script in debug mode for $($path)"

The rest of the script is essentially the same. I’ve updated the download link on the original post.  Or you can download the revised file here.