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:

$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.


# Function that lists the children of a dir
function Show-TreeItems

# Function that indents to a level i
function Indent
$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
Show-TreeItems $Child.PSPath


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

5 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

  2. Greetings: You have used BLOCKQUOTE tags, but your theme says it allows Code tags. If you surround your code above in CODE tags, as Timmothy Green has done, your two dashes should remain.
    I’ll test here, but comment smay be treated different from the main post:
    These — are two dashes with no tags

    Two — dashes with a blockquote tag.

    Two dashes -- with a Code tag. .

Leave a Reply