I want to print a directory tree excluding a folder. I already know the basic way to print the tree like this:
tree /A > tree.txt
I want to achieve something like this:
tree /A [exclude folder node_modules] > tree.txt
I want to print a directory tree excluding a folder. I already know the basic way to print the tree like this:
tree /A > tree.txt
I want to achieve something like this:
tree /A [exclude folder node_modules] > tree.txt
In Powershell, just use Where-Object and exclude the folder names you want (put a
*
wildcard on the front since it can be difficult to know how many spaces and special characters are on the same line as the folder name):tree /A | Where-Object {$_ -notlike "*node_modules"} > tree.txt
Edit: This won't exclude subfolders though, it will only exclude the folders you name in the Where-Object clause.
cmd.exe
's internaltree
command does not support excluding directories.If you only need to exclude directories by name themselves and not also their entire subtree (child directories and their descendants), see nferrell's answer.
If you need to exclude the entire subtree of directories matching a given name, more work is needed - see below.
Below is the source code for PowerShell function
tree
, which emulates the behavior ofcmd.exe
'stree
command, while also:offering selective exclusion of subtrees by name
Note: You may specify multiple names separated by
,
and the names can be wildcard patterns - note that they only apply to the directory name, however, not the full path.offering cross-platform support
Note: Be sure to save your script with UTF-8 encoding with BOM for the script to function properly without
-Ascii
.offering switch
-IncludeFiles
to also print files.With the function below loaded, the desired command looks like this:
Run
tree -?
orGet-Help tree
for more information.This isn't exactly a complete answer, but should allow you to accomplish what you want with a little work. If you used the
Show-Tree
code from the PowerShell Community Extensions as a base, and then added in something to filter out folders, you could accomplish what you desire. This is something that should be totally doable, really, since this little bit of code shows how to define a string to exclude (wildcards accepted in a-like
format), then get a recursive folder structure and denote if that is an excluded folder, or is contained within an excluded folder.When I ran this against my user profile it showed that it caught both a 'Temp' folder and a 'Template' folder, and marked those and each subfolder of those to be excluded. You should be able to get the code of the
Show-Tree
command by doing:Then you would just need to devise how to incorporate something similar to what I have above into that code, and you can make a new function to accomplish what you want.