How to Print a Directory Structure Using PowerShell: Step-by-Step Guide
If you need to print out the directory structure and list the files within, this PowerShell script will help you do just that. Follow the steps below to generate a detailed directory tree and save it to a file.
PowerShell Script to Print Directory Structure
To print and save the directory structure of a folder, use the following PowerShell script:
Tree "C:\Root" /f /a | Select-Object -Skip 5 | Set-Content C:\Root\dir.txt
Explanation of the Script Components
- Tree “C:\Root” /f /a: This command generates a directory tree.
- /f: Displays the names of the files in each directory.
- /a: Uses text characters instead of graphic characters to show the lines that link subdirectories.
- Select-Object -Skip 5: Skips the first 5 lines of the output, which usually contains header information.
- Set-Content C:\Root\dir.txt: Saves the output to a file named
dir.txt
in theC:\Root
directory.
Sample Output
The script will produce a text file (dir.txt
) with the following structure:
+---Test1
| | File1.txt
| | File2.txt
| | File3.txt
| |
| +---Test1.1
| | File1.txt
| | File2.txt
| |
| \---Test1.2
| File1.txt
|
+---Test2
| File1.txt
| File2.txt
| File3.txt
|
+---Test3
| \---Test3.1
| File1.txt
| File2.txt
|
\---Test4
File1.txt
Why Use This Script?
This PowerShell script is especially useful for:
- Documenting directory structures for project documentation.
- Explaining directory layouts to both technical and non-technical colleagues.
- Auditing file and folder structures for organization and management.
Conclusion
By using this PowerShell script, you can easily create a visual representation of any directory structure and its contents. This method is efficient and can be a valuable tool for various administrative and documentation tasks.
I hope this guide helps you manage and present your directory structures more effectively!
More posts on PowerShell and other scripts.
tree isn’t a powershell command. tree.com is a actually an old CMD utility. Output probably can’t be incorporated into the pipeline.