Use PowerShell to generate a list of files and directories

YetAnotherRandomUser picture YetAnotherRandomUser · Dec 12, 2014 · Viewed 57.7k times · Source

I'm writing a PowerShell script to make several directories and copy a bunch of files together to "compile" some technical documentation. I'd like to generate a manifest of the files and directories as part of the readme file, and I'd like PowerShell to do this, since I'm already working in PowerShell to do the "compiling".

I've done some searching already, and it seems that I need to use the cmdlet "Get-ChildItem", but it's giving me too much data, and I'm not clear on how to format and prune out what I don't want to get my desired results.

I would like an output similar to this:

Directory
     file
     file
     file
Directory
     file
     file
     file
     Subdirectory
          file
          file
          file

or maybe something like this:

+---FinGen
|   \---doc
+---testVBFilter
|   \---html
\---winzip

In other words, some kind of basic visual ASCII representation of the tree structure with the directory and file names and nothing else. I have seen programs that do this, but I am not sure if PowerShell can do this.

Can PowerShell do this? If so, would Get-ChildItem be the right cmdlet?

Answer

Matt picture Matt · Dec 12, 2014

In your particular case what you want is Tree /f. You have a comment asking how to strip out the part at the front talking about the volume, serial number, and drive letter. That is possible filtering the output before you send it to file.

$Path = "C:\temp"
Tree $Path /F | Select-Object -Skip 2 | Set-Content C:\temp\output.tkt

Tree's output in the above example is a System.Array which we can manipulate. Select-Object -Skip 2 will remove the first 2 lines containing that data. Also, If Keith Hill was around he would also recommend the PowerShell Community Extensions(PSCX) that contain the cmdlet Show-Tree. Download from here if you are curious. Lots of powerful stuff there.