-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGet-DirectoryStructure.ps1
More file actions
69 lines (56 loc) · 2.61 KB
/
Get-DirectoryStructure.ps1
File metadata and controls
69 lines (56 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Get-DirectoryStructure.ps1
function Get-DirectoryStructureFormatted {
# Function to recursively get the directory structure as a formatted string.
# Now supports excluding folders from the tree output.
param(
[string]$Path,
[string]$Indent = "",
[string[]]$ExcludeFolders = @()
)
$childItems = Get-ChildItem -Path $Path -ErrorAction SilentlyContinue
# Separate directories and files and sort them by name for consistent order
$directories = $childItems | Where-Object {$_.PSIsContainer} | Sort-Object Name
$files = $childItems | Where-Object {!$_.PSIsContainer} | Sort-Object Name
# Filter out excluded folders
if ($ExcludeFolders.Count -gt 0) {
$directories = $directories | Where-Object {
$dirName = $_.Name
$excluded = $false
foreach ($excPattern in $ExcludeFolders) {
if ($dirName -eq $excPattern -or $dirName -like $excPattern) {
$excluded = $true
break
}
}
-not $excluded
}
}
$outputLines = @() # Use an array to build lines
$totalChildrenCount = $directories.Count + $files.Count
$processedChildrenCount = 0
# Process directories
foreach ($dir in $directories) {
$processedChildrenCount++
$isThisChildTheVeryLast = ($processedChildrenCount -eq $totalChildrenCount)
# Determine the prefix for the current directory entry
$linePrefix = if ($isThisChildTheVeryLast) { "└── " } else { "├── " }
$outputLines += "$Indent$linePrefix$($dir.Name)"
# Determine the indent for the children of this directory
$childIndentContinuation = if ($isThisChildTheVeryLast) { " " } else { "│ " }
$recursiveResult = Get-DirectoryStructureFormatted -Path $dir.FullName -Indent ($Indent + $childIndentContinuation) -ExcludeFolders $ExcludeFolders
if (-not [string]::IsNullOrEmpty($recursiveResult)) {
# Add the multi-line result from recursion to our output lines
$outputLines += $recursiveResult
}
}
# Process files
foreach ($file in $files) {
$processedChildrenCount++
$isThisChildTheVeryLast = ($processedChildrenCount -eq $totalChildrenCount)
# Determine the prefix for the current file entry
$linePrefix = if ($isThisChildTheVeryLast) { "└── " } else { "├── " }
$outputLines += "$Indent$linePrefix$($file.Name)"
}
# Join all collected lines with newlines
return $outputLines -join "`n"
}