Create a Directory Tree with Powershell

I was playing around with PSDrives when I decided to write this script. It recurses through (part of) a PSDrive and shows the items it finds in a simple tree view.
The fun part is that it works on any PSDrive!

  • Show-Tree D:\scripts will show subdirectories and files in a tree;
  • Show-Tree HKCU:\ will show Registry keys and subkeys in a tree;
  • Show-Tree VI:\ will show your VMware Virtual Infrastructure in a tree, if you first create a PSDrive for it.

Here’s how to create a PSDrive for you Virtual Infrastructure:

Connect-VIServer MYVISERVER
$root = Get-Folder -NoRecursion
New-PSDrive -Name VI -PSProvider VIMInventory -Root ‘\’ -Location $root

Creating a full tree takes plenty of time, but you can get a branch of the full tree like so: Show-Tree VI:\MYDATACENTER\host\MYFOLDER\MYCLUSTER, where you replace the caps with your own names. Use vm instead of host to show the Virtual Machines and Templates view instead of the Hosts and Clusters view.
Hugo

Param($BaseDir)

# Function that lists the children of a dir
function Show-TreeItems
{
Param($Location)

# Function that indents to a level i
function Indent
{
Param([Int]$i)
$Global:Indent = $null
For ($x=1; $x -le $i; $x++)
{
$Global:Indent += ” “
}
}

$Children = Get-ChildItem $Location | Sort Name
ForEach ($Child in $Children)
{
Indent $i
“{0}{1}” -f $Indent,$Child
If ($Child.PSIsContainer)
{
# Recurse through subdir
$i++
Show-TreeItems $Child.PSPath
$i– # NOTE THERE SHOULD BE TWO MINUS SIGNS HERE
}
}

}

# Actual start of script
$i = 0
Show-TreeItems $BaseDir

»crosslinked«

4 thoughts on “Create a Directory Tree with Powershell”

  1. Excellent. I found the output easier to read if I replaced $Global:Indent += ” “ with $Global:Indent += [char]9 #tab

Leave a Reply