Skip to content

Commit 6dc4b02

Browse files
committed
Added script for printing directoy trees
1 parent f96ef97 commit 6dc4b02

1 file changed

Lines changed: 82 additions & 0 deletions

File tree

scripts/ShowDirectoryTree.ps1

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
<#
2+
.SYNOPSIS
3+
Displays a directory tree with indentation and optional depth control.
4+
5+
.DESCRIPTION
6+
This script shows the contents of a directory recursively up to a specified depth.
7+
Each entry is listed with its name and type (Dir/File), indented to reflect hierarchy.
8+
Hidden and system items can optionally be included using the -IncludeHidden switch.
9+
10+
.PARAMETER Path
11+
The base directory path to display. Defaults to the current directory.
12+
13+
.PARAMETER MaxDepth
14+
The maximum recursion depth. Defaults to unlimited depth.
15+
16+
.PARAMETER IncludeHidden
17+
Include hidden and system files and directories if specified.
18+
19+
.EXAMPLE
20+
.\Show-Tree.ps1 -Path "C:\Projects" -MaxDepth 2
21+
22+
.EXAMPLE
23+
.\Show-Tree.ps1 -Path "." -IncludeHidden
24+
25+
.NOTES
26+
Author: ChatGPT (GPT-5)
27+
Last updated: 2025-10-16
28+
#>
29+
30+
param(
31+
[string]$Path = ".",
32+
[int]$MaxDepth = [int]::MaxValue,
33+
[switch]$IncludeHidden
34+
)
35+
36+
function Show-Tree {
37+
<#
38+
.SYNOPSIS
39+
Recursive helper function for displaying directory trees.
40+
.DESCRIPTION
41+
Lists the files and directories under a given path with indentation.
42+
Traverses recursively up to a specified depth, and optionally includes hidden files.
43+
.PARAMETER Path
44+
The current directory to process.
45+
.PARAMETER MaxDepth
46+
The maximum recursion depth.
47+
.PARAMETER CurrentDepth
48+
The current recursion level (used internally).
49+
.PARAMETER IncludeHidden
50+
Include hidden/system items if specified.
51+
#>
52+
param(
53+
[string]$Path,
54+
[int]$MaxDepth,
55+
[int]$CurrentDepth = 0,
56+
[switch]$IncludeHidden
57+
)
58+
59+
if ($CurrentDepth -ge $MaxDepth) { return }
60+
61+
# Collect directory contents (with or without hidden files)
62+
if ($IncludeHidden) {
63+
$items = Get-ChildItem -LiteralPath $Path -Force | Sort-Object PSIsContainer, Name
64+
}
65+
else {
66+
$items = Get-ChildItem -LiteralPath $Path | Sort-Object PSIsContainer, Name
67+
}
68+
69+
foreach ($item in $items) {
70+
$indent = ' ' * ($CurrentDepth * 2)
71+
$type = if ($item.PSIsContainer) { 'Dir ' } else { 'File' }
72+
Write-Host ("{0}{1} {2}" -f $indent, $type, $item.Name)
73+
74+
# Recurse into subdirectories
75+
if ($item.PSIsContainer) {
76+
Show-Tree -Path $item.FullName -MaxDepth $MaxDepth -CurrentDepth ($CurrentDepth + 1) -IncludeHidden:$IncludeHidden
77+
}
78+
}
79+
}
80+
81+
# --- Run the function with top-level parameters ---
82+
Show-Tree -Path $Path -MaxDepth $MaxDepth -IncludeHidden:$IncludeHidden

0 commit comments

Comments
 (0)