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


Tagged with:

5 Responses to Create a Directory Tree with Powershell

  1. Hi, another great one :) Just one note: $i- has to be $i–

    Thanks for posting it. That’s one of the scripts I wanted to create but you save my time.

  2. admin says:

    Thank you David,
    You are absolutely right about the $i – – . For some reason the site software removes the second minus sign.

  3. […] This was quite a challenge. But I did it! Inspired by my scripts Create a Directory Tree with Powershell and Listing AD Group Members Recursively with Powershell, I responded to a queation in the VI […]

  4. Timmothy Green says:

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

  5. haakondahl says:

    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